Top 25 C# Interview Questions And Answers

C# (pronounced as C Sharp) is one of the famous and widely used Object Oriented Programming languages. This article is focused on the most frequently asked and important C# Interview Questions and Answers for freshers as well as an experienced software professional. 

These questions are gathered based on actual interview experience. Let’s begin to C# interview questions and answers.

C# Interview Questions


Frequently asked C# Interview Questions and Answers


Que 1. What is C#?

Answer: C# is an object-oriented programming language developed by Microsoft as part of its .Net initiative.

Que 2. What is OOP (Object Oriented Programming)?

Answer: Object-Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic. 

OOP allows decomposition of a problem into several entities i.e. objects and then builds data and functions around these objects. 

Associated functions can only access the data of the objects.

Que 3. What are the fundamental OOP Concepts in C#?

Answer: The Following are the main Object-Oriented concepts in C# or all the object-oriented programming languages.
  • Abstraction: Represent the essential feature without representing the background details
  • Encapsulation: Wrapping up a data member and a method together into a single unit
  • Inheritance: Object reusability
  • Polymorphism: Many forms of a single object
Click here to learn OOP concepts in detail.

What is Class and Object?

Class: Class is mandatory for representing data in any OOP language such as C#. A class is a core in C# or any Object-Oriented programming language. A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data. Use the “class” keyword flowed by class name to create a class.
Example:
class Student
{

} 
A class is only a logical representation of data hence it doesn’t occupy any memory space.

Object: Objects are the basic run-time entities of an object-oriented system. They may represent a person, a car, or any item that the program must handle.

An object is an instance of a class

A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.

When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.

When an object is created without the new operator, the memory will not be allocated in the heap, that means instance will not be created and the object in the stack contains the value null.

When an object is null then members of the class cannot be accessed by using that object.
Example:
class Student
{

}
Student studentObject = new Student(); 

studentObject is the object of the Student class. We can access data members and methods of the Student class by using student objects.

Que 4. What is an Interface?

Answer: An Interface is like a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.
  • An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.
  • An interface may define static methods, which must have an implementation.
  • Another way to achieve abstraction in C#, is with interfaces
Example:
interface IPerson
{
    void Address();
}

public class Student : IPerson
{
    public void Address()
    {
        Console.WriteLine("The is Student Address!");
    }
}

public class Employee : IPerson
{
    public void Address()
    {
        Console.WriteLine("The is Employee Address!");
    }
}
    
static void Main(string[] args)
 {
        Student student = new Student();
        student.Address();

        Employee employee = new Employee();
        employee.Address();

        Console.ReadLine();
    } 

Output:

C# Interview Questions


Que 5. What is a Destructor in C#?

Answer: A Destructor is used to clean up the memory and free the resources. Garbage collector is used to clean up the memory in C#.  System.GC.Collect() is called internally for cleaning up. However, sometimes it may be necessary to implement destructors manually. Example:
~Student()
{
    Console.WriteLine("Student class Destructor!");
} 


Que 6. What is a Struct in C#?

Answer: Struct is a value type in C#.
  • This is used to hold small date values.
  • In Struct, members are public by default.
  • No memory management for Struct.
Example:
struct Student
{
    public int Id;
    public string Name;
    public string Address;

    public Student(int id, string name, string address)
    {
        Id = id;
        Name = name;
        Address = address;
    }
}
    
static void Main(string[] args)
{
    Student student = new Student(1, "First Student", "100 Main Road, City, ST, 12345");
    Console.WriteLine("Student Details:\n Id: {0}\n Name: {1}\n Address: {2}", student.Id, student.Name, student.Address);
    Console.ReadLine();
} 
Output:
C# Interview Questions


Que 7. What is difference between Class and Struct in C#?

Answer: Following are the differences between Class and Struct in C#: 

ComparisonClassStruct
TypeClass is Pass by reference (reference type)Struct is Pass by Copy (Value type)
InheritanceClass supports InheritanceStruct does not supports Inheritance
ImplementationIt's implemented by implementing the IDisposable interface Dispose() method.It's implemented with the help of a destructor in C++ & C#.
Default Accessibility ModifiersMembers are private by default in ClassMembers are public by default in Struct
Memory ManagementUse Garbage collector for memory managementCannot use Garbage Collector so no memory management
DestructorClass can have a DestructorStruct doesn't have Destructor


Que 8. What is difference between class and interface in C#?

Answer: Following are the differences between Class and Struct in C#: 

ComparisonClassInterface
NatureClass has definition and implementationStruct is Pass by Copy (Value type)
InheritanceClass supports InheritanceStruct does not supports Inheritance
ConstructorA Class contains constructorAn Interface does not contain constructor
Accessibility ModifierA Class can have accessibility modifier for the subs, properties and functionsAn Interface cannot to have accessibility modifier. By default, everything is public
MembersA Class can contain data members and methods with the complete definitionAn Interface contains the only signature of members.
Static MembersI Class can contain static membersAn Interface cannot contain static members


Que 9. What are the different types of classes in C#?

Answer: Following are the different types of class in C# are:

  • Partial Class: Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
  • Sealed Class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class.  It is denoted by the keyword Sealed.
  • Abstract Class:  It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method.  It is denoted by the keyword abstract.
  • Static Class: It is a class that does not allow inheritance. The members of the class are also static.  It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

Que 10. What happens if the inherited interfaces have conflicting method names?

Answer: If we implement multiple interfaces in a class with conflict method names so we don’t need to define all or in other words, we can say if we have conflict methods in the same class so we can’t implement their body independently in the same class because of the same name and same signature so we have to use interface name before method name to remove this method confiscation.
Example:
interface iInterface1
{
    void Show();
}
interface iInterface2
{
    void Show();
}

class Student : iInterface1, iInterface2
{
    void iInterface1.Show()
    {
        Console.WriteLine("For iInterface1!");
    }
    void iInterface2.Show()
    {
        Console.WriteLine("For iInterface2!");
    }
}

static void Main(string[] args)
{
    iInterface1 obj1 = new Student();
    iInterface1 obj12 = new Student();
    iInterface2 obj2 = new Student();
    obj1.Show();
    obj12.Show();
    obj2.Show();

    Console.ReadLine();
} 

Output:

C# Interview Questions

This is one of the tricky C# Interview Questions. You have to be very careful while giving the answer.

Que 11. What is Boxing and Unboxing in C#?

Answer: Boxing: Converting a value type to reference type is called Boxing.
//Example: 
int intValue = 10;
object boxedValue = intValue; 
Unboxing: Explicit conversion of same reference type (created by boxing) back to value type is called Unboxing.
//Example:
int unBoxing = Convert.ToInt32(boxedValue); 


Que 12. What is Method Signature in C#?

Answer: The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
The important part here is that the return type of a method does not belong to its signature. So, you can’t overload methods that differ by return type only!

This is one of the frequently asked C# Interview Questions for the freshers and 1-2 years experienced software professional.

Que 13. How Exception Handling is implemented in C#?

Answer: Exception handling is done using the following 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 an exception handler.
  • finally – It is a block of code written to execute regardless of whether an exception is caught or not.
  • Throw – Throws an exception when a problem occurs.

Que 14. What is the difference between finally and finalize block in C#?

Answer: finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.

finalize method is called just before garbage collection. It is used to perform cleanup operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.


Que 15. What is the difference between the Virtual method and the Abstract method in C#?

Answer: 
Virtual Method: The virtual method must always have a default implementation. It can be overridden in the derived class, though not mandatory. An override keyword must be used to override the method in the derived class.

Abstract Method: The abstract method does not have an implementation. It resides in the abstract class. The derived class must implement the abstract method. An override keyword is not necessary here though it can be used.

Learn more about virtual keyword here
Learn more about abstract keyword here

Continue to C# Interview Questions and Answers

Que 16. Difference between ref and out keyword?

Answer: The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before being passed.
Examples:
//out
class OutExample
{
    static void Method(out int i)
    {
        i = 10;
    }
    static void Main()
    {
        int value;
        Method(out value);
        //output: 10
    }
} 
//ref
class RefExample
{
    static void Method(ref int i)
    {           
        i = i + 10;
    }
    static void Main()
    {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);
        //output: 11
    }
} 

Although variables passed as an out argument need not be initialized before being passed, the calling method is required to assign a value before the method returns.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore, methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.

Que 17. What is a static method in C#?

Answer: C# supports two types of class methods, static methods, and non-static methods. Any normal method is a non-static method. Static methods are methods that are called on the class itself, not on a specific object instance.
  • Static methods are called by using the class name, not the instance of the class.
  • A static method can be invoked directly from the class level
  • We can overload static methods in C#
Example:
class Student
{
    public static void Test()
    {
        Console.WriteLine("Testing staatic method in C#");
    }       
}
    
static void Main(string[] args)
{
    Student.Test();
    Console.ReadLine();
} 
Output:
C# Interview Questions

The Console class and its Read and Write methods are an example of static methods. The following code example calls Console.WriteLine and Console.ReadKey methods without creating an instance of the Console class.

Again, this is one of the important and frequently asked C# Interview Questions.

Que 18. What is the extension method?

Answer: An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types. The extension methods are called as if they were instance methods from the extended type, Example: x is an object from int class, and we called it as an instance method in int class. Create an Extension Method: Create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).
Example:
public static class MyMathExtension
{
    public static int factorial(this int x)
    {
        if (x <= 1) return 1;
        if (x == 2) return 2;
        else
            return x * factorial(x - 1);
    }
}
static void Main(string[] args)
{
    int x = 4;
    Console.WriteLine("Output: " + x.factorial());
    Console.ReadLine();
} 
Output:
C# Interview Questions

Tips in Extension Methods Usage:

  • This keyword must be the first parameter in the extension method parameter list.
  • Extension methods are used extensively in C# 3.0 and a further version specially for LINQ extensions in C#, for example: 

                      int[] ints = { 10, 45, 15, 39, 21, 26 };
                      var result = ints.OrderBy(g => g);

  • Here, order by is a sample for extension method from an instance of IEnumerable<T> interface, the expression inside the parenthesis is a lambda expression.
  • It is important to note that extension methods can’t access the private methods in the extended type.
  • If you want to add new methods to a type, you don’t have the source code for it, the ideal solution is to use and implement extension methods of that type.
  • If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.
This is one of the important C# Interview Questions for everyone.


Que 19. What is an Array in C#?

Answer: An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.
Single Dimensional Array: A Single dimensional array is a linear array where the variables are stored in a single row.
Example:
int[] obj = new int[10];
int[] singleDArray = new int[5] { 5, 10, 15, 20, 25 }; 
Multidimensional Arrays: Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.
Example:
int[,] multiDArrays = new int[3, 2] { {4, 2 }, {3, 2 }, {7, 4 } }; 

Important Properties of an Array:

  • Length: Gets the total number of elements in an array.
  • IsFixedSize: Flag to indicate whether the array is fixed in size or not.
  • IsReadOnly: Flag to indicate whether the array is read-only or not.

Que 20. What is a Jagged Array?

Answer: A Jagged array is an array whose elements are arrays. It is also called as the “array of arrays”. The elements of a jagged array can be either single or multiple dimensions and can have different sizes.
Example:
int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[3] { 2, 4, 6};
jaggedArray[1] = new int[4] { 3, 4, 7, 9 };
jaggedArray[3] = new int[2] { 4, 8}; 

Que 21. What is Serialization in C#?

  • Answer: Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called Deserialization.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

Types of Serialization:

  • XML serialization: It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
  • SOAP: Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.
  • Binary Serialization: Allows any code to be converted to its binary form. It can serialize and restore public and non-public properties. It is faster and occupies less space.

Uses for Serialization:
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Developers can perform the following action by using serialization:

  • Sending the object to a remote application by using a web service
  • Passing an object from one domain to another
  • Passing an object through a firewall as a JSON or XML string
  • Maintaining security or user-specific information across applications

Que 22. What is LINQ? And how to use it in C#?

Answer: Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store.

Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
Examples:
LINQ extension:
using System;
using System. Linq;
class Program
{
    static void Main(string[] args)
    {
	  int[] array = { 1, 3, 5, 7 };
         Console.WriteLine("Average: " + array.Average());
    }
} 
Output:
C# Interview Questions
Query expression:
using System;
using System. Linq;
class Program
{
    static void Main(string[] args)
    {
        int[] intArray = { 1, 2, 3, 4, 7, 8 };
        
        var elements = from element in intArray
                       orderby element descending
                       where element > 2
                       select element;
        Console.Write("Descending Order: ");
        foreach (var element in elements) // Enumerate.
        {
            Console.Write(element + " ");
        }
        Console.WriteLine();
    }
}
 
Output:
C# Interview Questions


Que 23. What is Lambda Expression in C#?

Answer: A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type, as the following example shows:
Examples:
delegate int del(int i);
static void Main(string[] args)
{
    del delObj = x => x * x;
    int j = delObj(5); 
}

//Expression tree type:

using System.Linq.Expressions;

class Program
{
    static void Main(string[] args)
    {
        Expression<del> obj = x => x * x;
    }
} 

The => operator has the same precedence as an assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

LINQ and Lambda are not only very important C# Interview Questions but also very commonly used in the development.


Que 24. What is a Delegate in C#?

Answer: A Delegate is a variable that holds the reference to a method or multiple methods. Hence it is a function pointer or reference type. A Delegate is an abstraction of one or more function pointers (as existed in C++).

The best way to understand delegates is to think of them as a class. Just like a class, we can declare the delegate anywhere with whatever access level required. And to use a delegate you must have an instance of the delegate class.

Delegates provide a way to define and execute callbacks. Their flexibility allows you to define the exact signature of the callback, and that information becomes part of the delegate type itself.
  • Delegates are type-safe, object-oriented and secure
  • Delegate types are derived from the
  • Delegate class in the .NET Framework.
  • They have a signature and a return type.
  • Both Delegate and the method that it refers to can have the same signature.
  • Delegates can point to either static or instance methods.
  • Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime.
  • Delegates can call methods synchronously and asynchronously.
Example:
class Program
{
    //Delegate Declaration
    public delegate int AddNumbers(int a, int b);
    static void Main(string[] args)
    {
        // After the declaration of a delegate, the object must be created of the delegate using 
        //the new keyword.
        AddNumbers delObj = new AddNumbers(AddOperation);
        var total = delObj(3, 2);
        Console.WriteLine("Addition of two numbers: " + total.ToString());
        Console.ReadLine();
    }

    private static int AddOperation(int fnumber, int snumber)
    {
        return fnumber + snumber;
    }
} 
In the above example, we have a delegate AddNumbers which takes two integers value as parameters. Class Program has a method of the same signature as the delegate, called AddOperation ().

Main() which creates an object of the delegate, then the object can be assigned to AddOperation()  as it has the same signature as that of the delegate.
Output:
C# Interview Questions

Types of Delegates:

  • Single Delegate: A delegate that can call a single method.
  • Multicast Delegate: A delegate who can call multiple methods. + and – operators are used to subscribing and unsubscribing respectively.
  • Generic Delegate: It does not require an instance of a delegate to be defined. It is of three types, Action, Funcs, and Predicate.

Que 25. What are Events in C#?

Answer: Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress, and so on.

Programmatically, a class that raises an event is called a publisher, and a class that response/receives the event is called a subscriber. An event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events. public delegate void Notification(); public event Notification notifyEvent;
Example:
namespace TestApp
{
    public delegate string EventHandler(string str);
    class Program
    {        
        public event EventHandler myEvent;
        public Program()
        {
            this.myEvent += SayHello;
        }

        private string SayHello(string txt)
        {
            return "Hello " + txt;
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            string result = obj.myEvent("User!");
            Console.WriteLine(result);
            Console.ReadLine();
        }       
    }
} 
Output:
C# Interview Questions

Learn more about C# Delegates and Events here

Summary:

These are frequently asked C# interview questions and answers that every experience software professional or beginner should learn. This topic will be very helpful to everyone to prepare technical interview.