C# Interview Questions

The target audiences of this article are developers who are looking to sharpen their coding skills and prepare themselves for their technical c# interview. 

 Here, we are going to refer to 50+ essential questions and answers related to the c# programming language. These c# questions will help you to understand the technical concepts of the language and to increase the confidence for your next c# interview. 

 As a developer, we use these concepts daily. Still, we don’t have the ideas behind them at the top of your heads. So here are the questions in detail. Now let us look at those questions one by one.


1. What is a class?

A class is a template to create an object. It contains properties as well as methods. We can create many instances of objects from a single class.

Below is an example of a class.


2. What are the main concepts of object-oriented programming?

Encapsulation, abstraction, polymorphism, and inheritance are the main concepts of object-oriented programming.


3. Explain Encapsulation

Encapsulation is a process of wrapping function and data members together in a class. It is like a capsule, a single unit.

Encapsulation is to prevent the unauthorized or unwanted change of data from outside of the function.

Below is an example of encapsulation.


4. What is abstraction?

Abstraction is the method of exposing only the required features of the class and hiding unnecessary information.

Let us try to understand it with the example of a motorbike

  • A rider knows the color, name, and model of the bike. Still, he does not know the internal engine and exhaust functionality.

So abstraction focuses on providing access to do a specific functionality without exposing how that functionality works internally.


5. What is polymorphism?

Polymorphism means the same method but different implementation.

There are two types of polymorphism.

Compile-time polymorphism – achieved by method overloading

Refer to the below example

Run time polymorphism – achieved by method overriding

Refer to the below example


6. What is Inheritance in C#?

When we create a class that can inherit the data members and the methods of another class (Parent class), it is called inheritance.

The class which inherits the properties and method is called child class, derived class or subclass. 

A class from which the child class inherits its properties and methods is a parent class or base class. 

Refer to the below example.

Output will be 1337, even though Class B doesn’t directly have any value.


7. What is an object?

An object is an instance of a class through which we access the functions of that class.  We can use the “new” keyword to create an object. A class that creates an object in memory holds information about the functions, data members, and behavior of that class.

Refer below for the syntax of an object.

8. What is a constructor, and what are its different types?

A constructor is like a method with the same name as the class, but it is a unique method. Even if it is not created, the compiler creates a default constructor in memory at the time of creating an object of the class.

  • The constructor is used to initialize the object with some default values.
  • Default constructor, parameterized constructor, copy constructor, static constructor, private constructor are different constructor types.

Refer to the below sample for different constructor types.


9. What is a destructor in C#?

The Destructor clears out the memory to free up resources. It is managed automatically by the garbage collector. System.GC.collect() is called internally for this purpose. However, if required, it can be done explicitly using a destructor.

Refer to the below example.


10. Is C# code managed or unmanaged code?

C# is managed code because Common language runtime compiles the code to Intermediate language.


11. What are value types and reference types?

We can categorize variables into value type and reference type. 

Variables of value type contain the value directly while the variable of a reference type contains the reference of the memory address where the value is stored actually in the memory.

For example bool, byte, int, char, and decimal are value type

And String, class, delegates are examples of reference types.

Below is the pictorial representation of the value type.

Below is the pictorial representation of the reference type.


12. What are namespaces, and is that compulsory?

A namespace is a way of organizing classes of the same group or functionality under the same name. We can call it a module. Although it is not compulsory to put class in a namespace.

Refer to the syntax below.


13. Explain types of comments in c# with examples.

There are three types of comments in c#.

  • Single line comments
  • Multiline comments
  • XML comments

Example of a single-line comment

//Hey, this is a single line comment

Example of a multi line comment

/*This is a multiline comment

written in two lines

2*/

Example of an XML comment

///Summary

///Here you can write anything

///summary


14. What is an interface? Give an example.

An interface is another form of an abstract class that has only abstract public methods, and these methods only have the declaration and not the definition. A class implementing the interface must have the implementation of all the methods of the interface.

For Example


15. How to implement multiple interfaces with the same method name in the same class?

If we want to implement multiple interfaces with the same method name, then we cannot directly implement the body of the function. We have to explicitly provide the name of the interface to implement the body of the method. In this way, the compiler decides which interface methods we are referring to, and this resolves the issue.

Let us see the below example.


16. What is the virtual method, and how is it different from the abstract method?

A virtual method must have a default implementation, and We can override this virtual method using the override keyword in the derived class.

The abstract method is without implementation, and it is created inside the abstract class only. In the case of an abstract class, the class derived from the abstract class must have an implementation of that abstract method.

Example of a virtual method.

Example of an abstract method.


17. What is method overloading and method overriding?

Method overloading is when we have a function with the same name but a different signature.

Method overriding is when we override the virtual method of a base class in the child class using the override keyword.

Both, method overloading and overriding are a type of polymorphism.


18. What is the static keyword?

We use the “static” keyword to create a static class, a static method, or static properties.

When we create a static class, then there can be only static data members and static methods in that class.

Static means that we cannot create the instance of that class. That class can be used directly like ClassName.methodName.

When there is a need for special functions, which are typical for all the instances of other classes, then we use static class.

For example, there is a requirement to load some default application-level values. We create a static class with static functions. That class is then accessible to all other classes without creating any instance. It also shares the same data with all the classes.

Refer to the below example.


19. Can we use “this” with the static class?

No, we cannot use “this” with the static class because we can only use static variables and static methods in the static class.


20. What is the difference between constants and read-only?

Constant variables have to be assigned a value at the time of declaration only, and we cannot change the value of that variable throughout the program. 

We can assign the value to the read-only variable at the time of declaration or in a constructor of the same class.

Here is an example of constants.

Here is an example of read-only.


21. What is the difference between string and string builder in C#?

A string is an immutable object. When we have to do some actions to change a string or append a new string, it clears out the old value of the string object, and it creates a new instance in memory to hold the new value in a string object. It uses System. String class, for example.

StringBuilder is a mutable object. It means that it creates a new instance every time for the operations like adding string (append), replace string (replace). It uses the old object only for any of the operations done to the string and thus increases the performance. It uses System.Text.StringBuilder class, for example.

The output of both the program is the same, “Hello World.”


22. Explain the “continue” and “break” statement.

We can use continue and break statements in a loop in c#. Using a break statement, we can break the loop execution, while using the continue statement, we can break one iteration of the loop.

An example of the break statement.

Here is the same example with a continue statement.


23. What are boxing and unboxing?

Conversion of value type datatype to reference type (object) datatype is called boxing.

Unboxing is the conversion of reference type datatype to value type.

For Example: 


24. What is a sealed class?

We use a “sealed” keyword to create a sealed class. Classes are created as a sealed class when there is no need to inherit that further or when there is a need to restrict that class from being inherited.

Refer to the syntax below.


25. What is a partial class?

There is a feature in the c# language to divide a single class file into multiple physical files. To achieve this, we have to use the “partial” keyword. At compile time, it is logically one file only. So we cannot have a method with the same name or a variable with the same name in two different partial class files. 

Here, to facilitate the developers to break down the big class files into multiple small physical files, this feature is provided.


26. What is enum?

In c# the “enum” keyword is used to declare an enumeration. An enum is a value type. It is a collection of related named constants referred to as an enumerator list. 

An enum type can be any of these (int, float, double, and byte). However, to use it beside int, explicitly casting is required.

To create a numeric constant in the .NET framework enum is used. All the members of the enum are of enum type, and there must be a numeric value for each enum type.

Int is the default type of the enumeration element. By default, the first enumerator has the value 0. The value of each successive enumerator is then increased by 1.

Refer to the below syntax:


27. What is dependency injection, and how can it be achieved?

Dependency injection is a design pattern. Here, instead of creating an object of a class in another class (dependent class) directly, we are passing the object as an argument in the constructor of the dependent class. It helps to write loosely coupled code and helps to make the code more modular and easy to test.

There are 3 ways to achieve dependency injection.

  • Constructor Injection: This is the most commonly used Injection type. In constructor injection, we can pass the dependency into the constructor. We have to make sure that we do not have a default constructor here, and the only one should be a parameterized constructor.
  • Property Injection: There are cases when we need the default constructor of a class, so in that case, we can use property injection.
  • Method Injection: In method injection, we need to pass the dependency in the method only. When the entire class does not require that dependency, there is no need to implement constructor injection. When we have a dependency on multiple objects, then instead of passing that dependency in the constructor, we pass that dependency in the function itself where it is required.

28. The “using” statement.

The keyword “using” is used to define the scope of the resources used in that using statement block. All the resources used inside the using code block get disposed of once the code block completes execution.

Refer to the below example.


29. What are the access modifiers? Explain each type.

Access modifiers are keywords used to provide accessibility to a class, member, or a function.

Below are its types

  • Public: Can be accessed anywhere without any restriction
  • Protected: Access is limited up to the class, which inherits this class.
  • Internal: Can be accessed only within the current assembly.
  • Private: Cannot be accessed outside.

Syntax of access modifier


30. What are delegates?

Delegates are like function pointers. It is a reference data type that holds the reference of a method. We use delegates to write generic type-safe functions. All delegates derive from System. Delegate.

A delegate can be declared using the delegate keyword followed by a function signature, as shown below.

The Following are the characteristics of delegates.

  • Delegates derive from the System. Delegate class.
  • Delegates have a signature as well as return type. A function assigned to delegates must be fit with this signature.
  • Delegates can point to instance methods or static.
  • Delegate objects, once created, can dynamically invoke the methods it points to at runtime.
  • Delegates can call methods synchronously and asynchronously.

Refer to below example


31. What are the different types of delegates?

There are three types of delegates.

  • Single Delegate: Single Delegate can invoke a single method.
  • Multicast Delegate: Multicast delegates can invoke multiple methods. The delegate method can do multicasting. We can add a method in the delegate instance using + operator, and we can remove a method using – operator. All the methods are invoked in sequence as they are assigned.
  • Generic Delegate:  .Net Framework 3.5 Introduces Generic delegates. There is no need to create an instance in a generic delegate.


32. What is an array? Explain Single and multi-dimensional arrays.

The array stores the value of the same type. It is a collection of variable stores into a memory location.

For example

int[] marks = new int[3] { 25, 34, 89 };

A single-dimensional array is a linear array. Single-dimensional array stores variables in a single row. The above example is a single-dimensional Array.

Arrays can have more than one dimension. Multi-dimensional arrays are also called rectangular Arrays.

For example

int[,] numbers = new int[3, 2] { { 1, 2 }, { 2, 3 }, { 3, 4 } };


33. What is the difference between the System.Array.CopyTo() and System.Array.Clone() ?

Using the Clone() method, we can create a new array object containing all the elements of the original array and using the CopyTo() method. All the items of existing array copies into another existing array. Both ways create a shallow copy.


34. What is the difference between array and arraylist?

When we want to store the items of the same type, then the array is used. The array has a fixed size but not in the case of an arraylist. We can store any type of data type in an array list.

Refer to the example of an array and array list.


35. What is a jagged array in C#?

A jagged array is like a nested array; each element of a jagged array is an array in itself. The item of a jagged array can be of different dimensions and sizes.

A jagged array is a special type of array introduced in c#. A Jagged array is an array of an array in which the length of each array index can differ.

Refer to the below example.


36. What is the difference between struct and class?

Class and struct are both user-defined but have a significant difference.

Struct

  • A Struct inherits from System. Value type and so it is a value type.
  • It is preferred to use struct when there is a small amount of data. 
  • A structure cannot be abstract.
  • There is no need to create an object with a new keyword.
  • Struct does not have permission to create any default constructor.

Syntax of struct

Class

  • The class is a reference type in c#, and it inherits from the System. Object Type.
  • When there is a large amount of data, then in that scenario, classes are used.
  • We can inherit one class from another class.
  • A class can be an abstract type.

37. What is the difference between throw and throw ex?

“Throw” statement holds the original error stack of the previous function or function hierarchy. In contrast, “Throw ex” has the stack trace from the throw point.  So it is always advised to use “Throw” because it provides exact error information related to the function and gives you actual trace data of error source.


38. Explain the difference between finally and finalize block?

Finally, it is a code block part of execution handling this code block executes irrespective of whether the exception occurs or not.

While the finalize method is called just before garbage collection. The compiler calls this method automatically when not called explicitly in code.


39. Explain var and dynamic.

We can declare the var type of a variable without specifying the .net data types explicitly. The compiler automatically detects the type of a variable at the compile-time based on the value assigned to it. We cannot declare a var type variable without assigning a value to it. The value of the var type variable cannot be changed later in the code.

Dynamic is the opposite of var. We can change the value of a variable of type dynamic in the code later. It also decides the type of the variable based on the value assigned to it. 

Like at the time of creating a variable of type dynamic, a value of Integer type is assigned to it, then also in the code further, we can assign a string type value to that variable. It holds the last changed value and acts like the data type of the latest values it holds.

Let us see the example to understand it in more detail.

In the above example, if we declare the variable “someValue ” to type var instead of dynamic, it throws an error. The reason for that error is that in the next line, we changed the value of the variable and assigned a string value.


40. What are Anonymous types in C#?

Anonymous types allow us to create new types without defining them. 

When there is a need to define read-only properties in a single object without defining each type. In that case, we use anonymous types. Here, a compiler generates type and is accessible only for the current block of code.

Refer to the below example.


41. What is multithreading, and what are its different states?

Any code block in c# runs in a process called a thread, and it is the execution path of the program. Usually, an application runs in a single thread. But multithreading helps to run the application in multiple threads. Using multithreading, we can divide the execution of our process among different threads to execute it simultaneously.

In multithreading, we can create multiple threads and assign particular tasks or put a code block to get executed. In this way, we can run more than one task at a time. This code block executes simultaneously and can save time, and in this way, we can make programs more efficient and fast.

Thread has its lifecycle, which includes various states of thread.

Aborted256The thread state includes AbortRequested and the thread is now dead, but its state has not yet changed to Stopped.
AbortRequested128The Abort(Object) method has been invoked on the thread, but the thread has not yet received the pending ThreadAbortException that will attempt to terminate it.
Background4The thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the IsBackground property.
Running0The thread has been started and not yet stopped.
Stopped16The thread has stopped.
StopRequested1The thread is being requested to stop. This is for internal use only.
Suspended64The thread has been suspended.
SuspendRequested2The thread is being requested to suspend.
Unstarted8The Start() method has not been invoked on the thread.
WaitSleepJoin32The thread is blocked. This could be the result of calling Sleep(Int32) or Join(), of requesting a lock – for example, by calling Enter(Object) or Wait(Object, Int32, Boolean) – or of waiting on a thread synchronization object such as ManualResetEvent.
Source: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadstate?redirectedfrom=MSDN&view=netcore-3.1

42. How is exception handling done in C#?

Try, catch, finally, and throw. These are the keywords used to handle the exception.

Below is the explanation of each keyword.

  • Try: We keep the code in the try block for which we want to handle the exception.
  • Catch: When any exception occurs in a try block, then it is caught in a catch block with the help of an exception handler.
  • Finally: To execute a code block irrespective of error, we place that code in the finally block to get executed.
  • Throw: Throws an exception when an issue occurs.

Below is the example of exception handling.


43. What are the custom exceptions?

Sometimes some errors need to be caught as per user requirements. Custom exceptions are used for them and are user-defined exceptions.

Refer to the below example.


44. What is LINQ in C#?

Language integrated query is the full form of LINQ. It is a method of querying data using the .net capabilities and c# syntax similar to SQL query.

The advantage of LINQ is that we can query different sources of data. The data source could be either collection of objects, XML files, JSON files, In-memory data or lists or, database objects. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Below is the syntax of LINQ.


45. What is serialization?

When we want to send an object through a network, then we have to convert that object into a stream of bytes. Serialization is a process of converting an object into a stream of bytes. To facilitate the object for serializable, it should implement ISerialize Interface. The process of De-serialization is the reverse process of creating an object from a stream of bytes. 


46. What are generics in c#?

Generics increase performance, increase type safety, reduce repeated code, and makes reusable code. Using generics, we can create collection classes. It is preferred to use System.Collections.Generic namespace instead of classes such as ArrayList in the System.Collections namespace to create a generic collection.

Generics encourages the usage of parameterized types. Refer to the example below.


47. What is reflection?

Reflection is when managed code can read its own metadata to find assemblies.

“Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Attributes.”

Source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection

The following information can be retrieved using reflection.

  • Assembly name
  • Class name
  • Method name
  • Object type
  • It Identifies properties and methods.

48. How to use nullable types?

In c#, we can also assign a null value to the variable. Such types are called nullable types.

Example below


49. Which is the parent class of all classes which we create in C#?

System.object.


50. Explain code compilation in C#.

Below are the steps explaining the code compilation.

  • The C# compiler compiles the code into managed code, also called Byte code.
  • Then JIT (Just in time compiler) compiles the Byte code into Native or machine language, which is directly executed by CPU.

Conclusion

Referring to the above questions and answers gives us in-depth knowledge of all essential concepts of c# language. These technical answers can help to sharpen our knowledge and helps to increase the grip on the language.