New 52 C# Developer Interview Questions And Answers

New 52 C# Developer Interview Questions And Answers

1. Can “this” be used within a static method?
Answer: We can’t use this in a static method because keyword ‘this’ returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and call with the name of a class not by instance so we can’t use this keyword in the body of static Methods, but in case of Extension Methods, we can use it the parameters of the function. Let’s have a look on “this” keyword.
The “this” keyword is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined. For example, consider the following class written in C#.

2. What are constructors in C#?
Answer: A constructor is a member function in the class and has the same name as its class. Whenever the object class is created, the constructor is automatically invoked. It constructs the value of data members while initializing the class.

3. What is static constructor?
Answer: A static constructor is used to initialize static data members as soon as the class is referenced the first time.

4. Can Multiple Inheritance implement in C#?
Answer: In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, user interface.

5. What is the difference between “continue” and “break” statements in C#?
Answer:
“continue” statement is used to pass the control to the next iteration. This statement can be used with – “while”, “for”, “for each” loops.
“break” statement is used to exit the loop.

6. What do you mean by boxing and unboxing in C#?
Answer:
Boxing – This is the process of converting from value type to reference type. For example,
int myvar = 10;
object myObj = myvar;
Unboxing – It’s completely opposite of boxing. It’s the process of converting reference type to value type. For example,
int myvar2 = (int)myObj;

7. How do you prevent a class from being inherited?
Answer:
The sealed keyword prohibits a class from being inherited.

8. List out the states of a thread in C#?
Answer:
Below are the states of thread –

  • Unstarted State
  • Ready State
  • Not Runnable State
  • Dead State

9. Explain the methods and properties of Thread class in C#?
Answer:

Below are the methods and properties of thread class –

  • CurrentCulture
  • CurrentThread
  • CurrentContext
  • IsAlive
  • IsThreadPoolThread
  • background
  • Priority

10. What is serialization?
Answer: If you want to transport an object through network then you have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called serialization.

11. What is the difference between abstract class and interface in C#?
Answer: An abstract class can have abstract and concrete methods whereas interface has only abstract methods.

12. What is a collection?
Answer: A collection works as a container for instances of other classes. All classes implement the ICollection interface.

13. Explain object pool in C#?
Answer: An object pool is used to track the objects which are being used in the code. So the object pool reduces the object creation overhead.

14. What are the types of delegates in C#?
Answer:

Below are the uses of delegates in C# –

  • Single Delegate
  • Multicast Delegate
  • Generic Delegate

15. Why are strings in C# immutable?
Answer: Immutable means string values cannot be changed once they have been created. Any modification to a string value results in a completely new string instance, thus an inefficient use of memory and extraneous garbage collection. The mutable System.Text.StringBuilder class should be used when string values will change.

16. Why use the keyword “const” in C#? Give an example?
Answer: “Const” keyword is used for making an entity constant. We can’t reassign the value to constant.

Eg: const string _name = “Test”;

17. Explain the “static” keyword in C#?
Answer: Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.
To know more go to the following link:
Difference Between Const, ReadOnly and Static ReadOnly in C#
Constant VS ReadOnly In C#.

18. Explain Copy constructor in C#?
Answer: If the constructor contains the same class in the constructor parameter then it is called as copy constructor.

class MyClass
public string prop1, prop2;
public MyClass(string a, string b)
prop1 = a;
prop2 = b;
public MyClass(MyClass myobj) // Copy Constructor
prop1 = myobj.prop1;
prop2 = myobj.prop2;

19. Explain Static constructor in C#?
Answer: If the constructor is declared as static then it will be invoked only once for all number of instances of a class. Static constructor will initialize the static fields of a class.

class MyClass
public string prop1, prop2;
public MyClass(string a, string b)
prop1 = a;
prop2 = b;

Static MyClass()
Console.WriteLine(“Static Constr Test”);
public MyClass(MyClass myobj) // Copy Constructor
prop1 = myobj.prop1;
prop2 = myobj.prop2;

20. Which string method is used for concatenation of two strings in c#?
Answer: “Concat” method of String class is used to concatenate two strings. For example,

the string.Concat(first, sector)

21. Define Multicast Delegate in C#?
Answer: A delegate with multiple handlers is called as a multicast delegate. The example to demonstrate the same is given below

public delegate void CalculateMyNumbers(int x, int y);
int x = 6;
int y = 7;
Calculate My Numbers add My Numbers = new Calculate My Numbers(FuncFor Adding Numbers);
Calculate My Numbers multiply My Numbers = new Calculate MyNumbers(Func For Multiplying Numbers);
Calculate My Numbers multi Cast = (Calculate My Numbers)Delegate. Combine (add My Numbers, multiply My Numbers);
multiCast. In voke(a,b);

22. What is the difference between constant and read-only in c#?
Answer: Constant (const) and Readonly (readonly) both look like same as per the uses but they have some differences:

Constant is known as “const” keyword in C# which is also known immutable values which are known at compile-time and do not change their values at run time like in any function or constructor for the life of application till the application is running.

Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call the constructor with “new” keyword. 

See the example

We have a Test Class in which we have two variables one is readonly and another is constant.
class Test {
readonly int read = 10;
const int cons = 10;
public Test() {
read = 100;
cons = 100;
public void Check() {
Console.WriteLine(“Read-only : {0}”, read);
Console.WriteLine(“const : {0}”, cons);
Here I was trying to change the value of both the variables in the constructor but when I am trying to change the constant it gives an error to change their value in that block which has to call at run time.
ASP.NET
So finally remove that line of code from class and call this Check() function like the following code snippet:
class Program {
static void Main(string[] args) {
Test obj = new Test();
obj.Check();
Console.ReadLine();

class Test {
readonly int read = 10;
const int cons = 10;
public Test() {
read = 100;
public void Check() {
Console.WriteLine(“Read only : {0}”, read);
Console.WriteLine(“const : {0}”, cons);
Output:

23. Difference between Equality Operator and Equals() Method in C#?
Answer: Both the == Operator and the equals() method is used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
using System;
namespace ComparisionExample {
class Program {
static void Main(string[] args) {
string name = “sandeep”;
string myName = name;
Console.WriteLine(“== operator result is {0}”, name == myName);
Console.WriteLine(“Equals method result is {0}”, name.Equals(myName));
Console.ReadKey();

24. Explain the features of C# ?
Answer:
Below are some of the features supported in C# –
Constructors and Destructors
Properties
Passing Parameters
Arrays
Main
XML Documentation and
Indexers.

25. List some of the advantages of C#?
Answer:

  • Below are the advantages of C# –
  • Easy to learn
  • Object-oriented
  • Component oriented
  • Part of .NET framework

26. What is a state-related codebase?
Answer: Well, it is a way to write code that basically replaces branching and conditional statements with functions and then some of those functions can be used to manage state within a class.

So, first things first and let’s start by turning conditions into functions. Let’s consider the following code.

27. Explain Polymorphism?
Answer: Programmatically, Polymorphism means the same method but different implementations.

It is of 2 types, Compile-time and Runtime.

Compile-time polymorphism is achieved by operator overloading.

Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.

For Example, If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

28. How is Exception Handling implemented in C#?
Answer:

Exception handling is done using four keywords in C#:

try – Contains a block of code for which an exception will be checked.
catch – It is a program that catches an exception with the help of exception handler.
finally – It is a block of code written to execute regardless whether an exception is caught or not.
Throw – Throws an exception when a problem occurs.

29. What is a Destructor in C#?
Answer: A Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.

For Example:

~Car()

Console.writeline(“….”);

30. Explain access modifier – “protected internal” in C#?
Answer: “protected internal” can be accessed in the same assembly and the child classes can also access these methods.

31. Explain String Builder class in C#?
Answer: This will represent the mutable string of characters and this class cannot be inherited. It allows us to Insert, Remove, Append and Replace the characters. “ToString()” method can be used for the final string obtained from StringBuilder. For example,
StringBuilder TestBuilder = new StringBuilder(“Hello”);
TestBuilder.Remove(2, 3); // result – “He”
TestBuilder.Insert(2, “lp”); // result – “Help”
TestBuilder.Replace(‘l’, ‘a’); // result – “Heap”

32. How we can sort the array elements in descending order in C# ?
Answer: “Sort()” method is used with “Reverse()” to sort the array in descending order.

33. List out some of the exceptions in C#?
Answer:
Below are some of the exceptions in C# –

  • NullReferenceException
  • ArgumentNullException
  • DivideByZeroException
  • IndexOutOfRangeException
  • InvalidOperationException
  • StackOverflowException etc.

34. What is the difference between string and StringBuilder in c#?
Answer: StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:
ASP.NET
Note:

It’s an immutable object that holds a string value.

Performance-wise string is slow because its’ create a new instance to override or change the previous value.

String belongs to System namespace.
StringBuilder:
System.Text.StringBuilder is a mutable object which also holds the string value, mutable means once we create a System.Text.StringBuilder object we can use this object for any operation like insert value in an existing string with insert functions also replace or append without creating a new instance of System.Text.String Builder for every time so it’s using the previous object so it’s work fast as compare than System.String. Let’s have an example to understand the System.Text.StringBuilder like:

ASP.NET
Note:

StringBuilder is a mutable object.
Performance-wise StringBuilder is very fast because it will use the same instance of StringBuilder object to perform any operation like insert value in the existing string.
StringBuilder belongs to System.Text.StringBuilder namespace.
For More details read this article by following the link:

Comparison of String and StringBuilder in C#
String and StringBuilder Classes

35. Can Multiple Catch Blocks execute in c#?
Answer: we can use multiple Catches block with every try but when any Exceptions is throw by debugger so every catches match this exception type with their signature and catch the exception by any single catch block so that means we can use multiple catches blocks but only one can executed at once like:
using System;
class MyClient {
public static void Main() {
int x = 0;
int div = 0;
try {
div = 100 / x;
Console.WriteLine(“Not executed line”);
} catch (DivideByZeroException de) {
Console.WriteLine(“DivideByZeroException”);
} catch (Exception ee) {
Console.WriteLine(“Exception”);
} finally {
Console.WriteLine(“Finally Block”);
Console.WriteLine(“Result is {0}”, div);

36. Explain Generics in C#?
Answer: Generics in c# is used to make the code reusable and which intern decreases the code redundancy and increases the performance and type safety.
Namespace – “System.Collections.Generic” is available in C# and this should be used over “System. Collections” types.

37. What are partial classes?
Answer: A partial class is only used to splits the definition of a class in two or more classes in the same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with the same object.

Partial Classes can be created in the same namespace it’s doesn’t allow to create a partial class in a different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in the same namespace, let’s have an example:

ASP.NET
For more go with the following link:

Partial Classes in C# With Real Example

38. What are Boxing and Unboxing?
Answer:

Boxing and Unboxing both are used for type conversion but have some difference:

Boxing: Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System. Object and stores it on the heap area in the application domain.

Example:

ASP.NET

Unboxing: Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing has to be explicit by code.

Example: The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object. (C# .Net Training Videos)

For more details read this:

  • Boxing and Unboxing
  • Type Conversions in C#

39. What is the difference between Interface and Abstract Class?
Answer: Theoretically there are some differences between Abstract Class and Interface which are listed below:

A class can implement any number of interfaces but a subclass can at most use only one abstract class.
An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods have to be abstract.
An abstract class can declare or use any variables while an interface is not allowed to do so.
In an abstract class, all data member or functions are private by default while in an interface all are public, we can’t change them manually.
In an abstract class, we need to use an abstract keyword to declare abstract methods while in an interface we don’t need to use that.
An abstract class can’t be used for multiple inheritances while the interface can be used as multiple inheritances.
An abstract class use constructor while in an interface we don’t have any type of constructor.
To know more about the difference between Abstract Class and Interface go to the following link:

Abstract Class vs Interface
Explore Interface Vs Abstract Class. (.net Training Online)

40. What is the difference between ref and out keywords?
Answer: In C Sharp (C#) we can have three types of parameters in a function. The parameters can be in parameter (which is not returned back to the caller of the function), out parameter and ref parameter. We have lots of differences in both of them.

ASP.NET

For more details go to the following link:

Ref Vs Out Keywords in C#
Ref And Out Keywords in C#

41. What is the Constructor Chaining in C#?
Answer: constructor chaining is a way to connect two or more classes in a relationship as Inheritance, in Constructor Chaining every child class constructor is mapped to parent class Constructor implicitly by base keyword so when you create an instance of child class to it’ll call parent’s class Constructor without it inheritance is not possible.

For more example follow the link:

Constructor Chaining in C#
Constructors in C#

42. What you understand by Value types and Reference types in C#.Net?
Answer: In C# data types can be of two types: Value Types and Reference Types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently operate on their values, Value Type member will be located into Stack and reference member will be located in Heap always.

Let consider each case briefly.

Pure Value Type: Here I used a structure as a value type. It has an integer member. I created two instances of this structure. Afterward, I assigned the second instance to the first one. Then I changed the state of the second instance, but it hasn’t affected the first one, as whole items are value type and assignments on those types will copy only values not references i.e. in a Value Type assignment, all instances have its own local copy of members.

Pure Reference Type: I created a class and added a “DataTable” as a Reference Type member for this class. Then I performed the assignments just like below. But the difference is that on changing the state of the second instance, the state of the first instance will automatically alter. So in a Reference Type assignment, both Value and Reference will be assigned i.e. all instances will point to the single object.

Value Type With Reference Type

This case and the last case to come are more interesting. I used a structure in this particular scenario also. But this time it includes a Reference Type(A Custom Class Object) Member besides a Value Type (An Integer) Member. When you performing the assignments, it seems like a swallow copy, as Value Type member of the first instance won’t affect, but the Reference Type member will alter according to the second instance. So in this particular scenario, assignment of Reference Type member produced a reference to a single object and assignment of Value Type member produced a local copy of that member.

Reference Type With Value Type

Contrary to the above case, in this scenario, both Reference & Value Types will be effected. I.e. a Value Type member in a Reference Type will be shared among its instances.
For more details follow this link:

C# Concepts: Value Type and Reference Type
Value Types and Reference Types Variables

43. What are Indexer in C# .Net ?
Answer: Indexer allows classes to be used in a more intuitive manner. C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not an essential part of object-oriented programming.

An indexer also called an indexed property, is a class property that allows you to access a member variable of a class using the features of an array.

Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator.

Creating an Indexer
< modifier > < return type > this[argument list] {
get {
// your get block code
set {
// your set block code
In the above code:

can be private, public, protected or internal.

44. Describe the accessibility modifiers in c#.Net?
Answer: Access modifiers are keywords used to specify the declared accessibility of a member or a type.

45. Why use access modifiers?
Answer: Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn’t have access to certain features.

In C# there are 5 different types of Access Modifiers.

ASP.NET

For details follow the link:

46. What are Access Modifiers in C#?
Access Specifiers (Access Modifiers) in C#46. What is Virtual Method in C#?
Answer: A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method’s basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member if no derived class has overridden the member.

Virtual Method

By default, methods are non-virtual. We can’t override a non-virtual method.
We can’t use the virtual modifier with the static, abstract, private or override modifiers.

47. What are the differences between IEnumerable and IQueryable?
Answer: Before the differences learn what is IEnumerable and IQueryable.

IEnumerable: Is the parent interface for all non-generic collections in System. Collections namespace like ArrayList, HastTable, etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
IQueryable: As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable. If the provider does not also implement IQueryable, the standard query operators cannot be used on the provider’s data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of “executing an expression tree” is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called. ASP.NET
IEnumerable vs IQuerable
IEnumerable Vs IQueryable.

48. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?Answer:
Clone: The method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

CopyTo: The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types. (Interview Questions and Answers)

49. What is the difference between late binding and early binding in c#?
Answer: Early Binding and Late Binding concepts belong to polymorphism so let’s see first about polymorphism:

Polymorphism is an ability to take more than one form of a function means with the same name we can write multiple functions code in a same class or any derived class.

Polymorphism we have 2 different types to achieve that:

Compile Time also known as Early Binding or Overloading.
Run Time also known as Late Binding or Overriding.
Compile Time Polymorphism or Early Binding:

In Compile time polymorphism or Early Binding, we will use multiple methods with the same name but a different type of parameter or maybe the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.

See how we can do that by the following example:

ASP.NET
Run Time Polymorphism or Late Binding:

Run time polymorphism also known as late binding, in Run-Time Polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allow that at compile time so we can use in derived class that bind at run time when a child class or derived class object will be instantiated that’s why we say that Late Binding. For that, we have to create my parent class functions as partial and in driver or child class as override functions with the override keyword.

  • Like the as following example:
  • ASP.NET
  • Understanding Polymorphism in C#
  • Polymorphism in .NET
  • For more detail follow the link
  • Overview of Arrays in C#
  • Doing Arrays – C#

50. What is the difference between “StringBuilder” and “String” in C#?
Answer: StringBuilder is mutable, which means once object for StringBuilder is created, it later be modified either using Append, Remove or Replace.
The string is immutable and it means we cannot modify the string object and will always create a new object in memory of string type.

51. Explain circular reference in C#?
Answer: This is a situation where in, multiple resources are dependent on each other and this causes a lock condition and this makes the resource to be unused.

52. What is IEnumerable<> in c#?
Answer: IEnumerable is the parent interface for all non-generic collections in System. Collections namespace like ArrayList, HastTable, etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this interface as a parent so we can’t use iteration by for each loop or can’t use that class object in our LINQ query.

ASP.NET
For more details go with the following link:

Implement IEnumerable Interface in C#
IEnumerable Interface in C#