Programming
AI/ML
Automation (RPA)
Software Design
JS Frameworks
.Net Stack
Java Stack
Django Stack
Database
DevOps
Testing
Cloud Computing
Mobile Development
SAP Modules
Salesforce
Networking
BIG Data
BI and Data Analytics
Web Technologies
All Interviews

Top 50 C# Interview Questions and Answers

9/Jan/2024 | 18 minutes to read

dotnet

Here is a List of essential C# Interview Questions and Answers for Freshers and mid level of Experienced Professionals. All answers for these C# questions are explained in a simple and easiest way. These basic, advanced and latest C# questions will help you to clear your next Job interview.


C# Interview Questions and Answers

These interview questions are targeted for C# Programming language, an object-oriented language. A .NET Developer or Testing Professional must know the answers of these frequently asked C# interview questions to clear the interview.


1. What is the latest version of C# with features?

C# 1.0 released in 2002. And the latest version is C# 11. For more you can visit Microsoft official site Releases . There are many new features in C# 12. For more you can visit What's new in C# 12.

2. What do you understand about Top-level statements in C#?

C# 9 introduced the concept of Top-level statements that allows you to write the code at the top level of a file without wrapping it in a class or method. Top-level statements are
  • Good when you are writing small scripts or console applications like Azure functions or GitHub Actions.
  • Not changing the existing way of programming, they are just an alternative where the compiler generates the main entry point for your application.
For more refer Top-level statements in C#.

3. Explain the primary constructors?

You can create Primary Constructors by adding parameters to a struct or class declaration. You can access primary constructor parameters throughout the class or struct scope. Primary constructor parameters are useful when
  • You want to pass them to the base constructor.
  • To pass parameters for Dependency Injection.
  • You want to reference it in an instance member.
  • To initialize property or field.
For more visit Primary Constructors.

3. How will you enable nullable reference types in a C# application?

Once you enable the nullable reference types, Compiler shows the warnings in the code for potential null reference exceptions where you have a null value and you have missed to check it. You can enable the nullable
  • At project level by adding the property enableto your .csproj file
  • By adding #nullable enable at the top of your file.
  • By adding #nullable enable around the code section.
For more visit Enable nullable reference types.

2. How will you differentiate readonly, const and static variables in c#?

  • const keyword allows you to declare a constant field or a constant local which you expect not to modify at any time in the code except at the declaration time you need to assign a value. For more visit c# const.
  • readonly keyword allows you to declare a field whose values can be assigned or modified at the declaration or in constructor only. For more visit c# readonly.
  • static keywords allows you to declare the static member which belongs to the type itself instead of object. Fields, Properties, methods constructors, operators, local functions from C# 8 and lambda expressions or anonymous methods from C# 9 onwards can be marked as static inside classes, interfaces or structs. For more visit c# static.

3. What are the three characteristics of Object Oriented Programming?

There are three main characteristics of Object Oriented Programming.
  • Encapsulation is considered as the first principle of OOPs. As per this principle, A Class or Struct can specify the accessibility of its members to code outside of this class. Members not intended to be accessed outside of this class or struct can be hidden. For more visit Object oriented - Encapsulation.
  • Inheritance is one of the three characteristics of OOPs. It allows you to create new classes that can re-use, modify and extend the behavior defined in other classes. In Inheritance, the class which inherits or re-use the other class members is known as derived class and the class whose members are inherited is known as Base class.
    C# does not allow multiple inheritance - means a derived class can have only one direct base class. Inheritance is transitive in nature means If class X inherits from class Y and class Y inherits from class Z then class X inherits from both Y and Z. For more visit Inheritance.
  • Polymorphism - It is referred to as the third pillar of Object oriented programming. Polymorphism means "Many shapes" - more than one form of an object. It allows you to implement inherited properties and methods in different ways across the abstractions. C# implement polymorphism at compile time and run time. For more visit Polymorphism.
For Object Oriented interview questions visit Object-Oriented Questions.

4. What is the difference between in, ref and out keywords?

  • in keyword is like ref or out keywords but 'in' arguments can not be modified by the called method. 'in' arguments must be initialized before passing to the called method. If you try to modify the value of 'in' argument in the calling method it will throw an error. So it's like a readonly variable. For more visit in keyword.
  • ref keyword causes an argument to be passed by reference and may be read or written by the called method. To pass an argument as reference means any change to the parameter in the called method is reflected in the calling method argument. ref argument may be modified by the called method. For more visit ref keyword.
  • out keyword causes arguments to be passed by reference and is written by a called method. It is similar to ref keyword, except that ref requires that the variable must be initialized before it is passed. To pass variables as out arguments, both the method definition and the calling method must explicitly use the out keyword. For more visit out keyword.
For more visit Passing parameters as value type or reference type.

5. Why does c# not support multiple Inheritance?

To understand this, First you need to understand the Diamond problem: diamond problem
The Diamond problem (It's also referred to as the "deadly diamond of death") is an ambiguity that occurs when two classes B and C inherit from Class A and class D inherits from both B and C. If a method in class D calls a method defined in A(and does not override the method), and B and C have already overridden that method differently, then from which class does it inherit: B or C?

6. What is method shadowing or method hiding in C#?

Shadowing is also known as method Hiding in C#. Shadowing is a VB.Net concept. It hides the base class method implementation. It can be achieved using the 'new' keyword. If a method is not overriding the derived method that means it's hiding it.
Override keyword is used to provide a completely new implementation of a base class method or extend base class method (which is marked 'Virtual') in the derived class. While the New keyword just hides the base class method, not extends it.
If you think you need a different implementation of the same function as provided by base class, then you can hide the base class function implementation in child class.

        class BC
        {
          public void Display()
          {
             System.Console.WriteLine("BC::Display");
          }
        }

        class DC : BC
        {
          public void Display()
          {
             System.Console.WriteLine("DC::Display");
          }
        }

        class Demo
        {
          public static void Main()
          {
             DC obj = new DC();
             obj.Display();
          }
        }

        Output : DC:Display
        
On compilation the above program will throw a warning which says test.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member 'BC.Display()'. Use the new keyword if hiding was intended. test.cs(3,15) So modify the code as below.

        class DC : BC
        {
          new public void Display()
          {
             System.Console.WriteLine("DC::Display");
          }
        }
        

7. How will you differentiate var, object and dynamic keywords in C#.

Let's take a look at this example to understand the difference.

    class Program
    {
    static void Main(string[] args)
    {
    var x = 10;
    object y = 20;
    dynamic z = 30;

    x = "test"; // Error -  Cannot implicitly convert type 'string' to 'int'

    y = "test";
    y = y - 10;  //Error Operator '-' cannot be applied to operands of type 'object' and 'int'

    z = "test";
    z = z - 10;
    Console.WriteLine("{0},{1},{2}",x,y,z);
    Console.ReadLine();
    }

    void display(var x){} // Error CS0825 - The contextual keyword 'var' may only appear within a in local variable declaration or script code.

    void display(object x){}

    void disp1(dynamic x){}
    }
  • var was introduced with C# 3.0, Variables declared at method scope level can have implicit type 'var'. var types are initialized at the time of declaration only and can store any value. Compiler determines the type of var type so it is similar to strongly typed. You can use a var type in the same scope where it is defined - refer example. Type casting is not required as the compiler has all information to perform operations. You can use a var type for constructor invocation expressions, anonymous type etc. For more visit var.
  • object is the part of C# 1.0, It is the base class of all types in .NET framework so it can store any type. Compiler has little information about the type. You can pass object type as method argument and can return object type from a method as in the above example. object types need type casting to perform operations and can cause the problem at run time if type casting is not performed. For more visit object.
  • dynamic was introduced with C# 4.0, Use of dynamic keyword with variable and it's members bypass the compile time type checking instead it resolves all operations at the runtime. You can pass dynamic type as method argument and method also can return dynamic type - refer example. Casting is not required as operations are resolved at runtime but you should have correct member information to use dynamic types. For more visit dynamic.

8. Can Virtual or Abstract members be declared private in C#?

No, It will throw a compile time error.


virtual void display() // will throw error here
        {
        // Implementation

        }

9. What is Boxing and Unboxing in C# ?

  • Boxing - When a value type is converted to the 'object' type or to any interface type implemented by this value type is known as Boxing. When CLR performs boxing on a value type it wraps the value inside a System.Object instance and that value is stored on a managed heap.
  • UnBoxing - When a value type is extracted from the 'Object' is called Unboxing.
Boxing is performed implicitly and Unboxing is implemented explicitly. Boxing and Unboxing example:

        int a = 13;
        // The below line assigns the value of int a to object o, it's boxing.
        object o = a;
        Now you can assign the value of o to integer a, it's unboxing.
        o = 13;
        a = (int)o;  // unboxing
        
For more visit Boxing and Unboxing in C#.

10. What is Method Overloading in C#?

Method Overloading is a way to implement polymorphism - you are going to have more than one form of a method. You can implement method overloading by defining two or more methods in a class with the same name but different method signatures. Method Signature includes number, sequence and type of parameters not the return type of method. Method overloading example:
 
                void check(int x)
                {
                // Implementation
                }
                void check(float x)
                {
                    // Implementation
                }
                void check(int x, int y)
                {
                    // Implementation
                } 
In the above example method name is the same 'check' in all three cases but method signature is different.

11. What is Value Type and Reference Type in C#?

C# has mainly two categories of the types.
  • Value types - A Value type variable holds an instance of the type and when you perform any assignment only an instance of the type is copied, not the reference of that instance. By default, when you pass an argument to a method, only variable value is copied. Value types include the following:
    • All numeric data types
    • Boolean, Char, and Date
    • All structures, even if the members of structure are reference types
    • An Enum type, since the underlying type of enum is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong.
    For more Value Types in C#.
  • Reference types - Variables of reference types contain the references (memory address) to an instance of the types.
    A reference type holds the address of a memory location that holds the actual data of the variable. So operations you perform on one variable can affect the object referenced by the another variable.
    C# offers some keywords to declare reference types including: class, interface, delegate, record and provides some built-in reference types like dynamic, object, string.
    For more Reference Types in C# and Value Types and Reference Types in C#.

12. What are the new features in C# 8.0?

To know more about C# 8.0 new features visit What's new in C# 8.0

13. How will you differentiate Abstraction and Encapsulation in C#?

  • Abstraction is to create the prototype of relevant attributes and interaction of an entity in the form of classes. This Prototype defines an abstraction representation of a concept. For example, A BankAccount base class creates an abstraction or defines the behavior for the Bank Account concept. Now you can create any type of bank account like saving, just by deriving your new class 'SavingAccount' from this 'BankAccount' base class.
  • Encapsulation is the hiding of the functionality and internal state of an object from the code outside of this class and allows access through a public set of properties or functions. For Example, the BankAccount class can contain some private members to hide the data from the code outside of this 'BankAccount' class.
  • Abstraction can be implemented using Abstract classes and Interface whereas Encapsulation can be implemented using access modifiers such as public, private, protected etc.
  • Abstraction helps to solve the problems at design level using Abstract classes or Interfaces while encapsulation helps to solve problems at implementation level using access modifiers.
For more visit Abstraction vs Encapsulation and Abstraction vs Encapsulation in C++.

14. Differentiate Abstract class and Interface in C#? Explain the usage of interface?

Abstract class and Interface allows you to define an abstraction in C#. But both have some differences.

  • Abstract class provides both declaration and implementation but Interfaces have only declaration.
  • When you want to achieve multiple inheritance then you should use Interface not Abstract class because in C#, a class can inherit from one class only but from more than one interface.
  • Abstract class contains constructors while Interface does not.
  • Interfaces have only public members whereas abstract classes can contain public, private protected modifiers.
  • Abstract class can provide complete, partial or no implementation whereas Interface provides only declaration.
  • Performance wise, Abstract class is fast as Interface needs to identify the actual method implementation which takes some time.
  • Interface provides you the ability of a class whereas An abstract class gives you the identity of class.
  • Abstract class allows you to define and implement some common functionality which can be used by many child classes but Interface gives you common method signatures that can be implemented differently as per requirement.
  • Abstract class can provide default implementation for any newly added method and all code will work properly but in case of Interface you need to implement that new method in all the classes using that interface.
  • Members of Interface can not be static but complete members of Abstract class can be static.
  • Interfaces allow you to create Mocks easily in unit testing while Abstract class needs extra coding.
For more visit Abstract class vs Interface C#.

15. What is Polymorphism? Explain the static and Dynamic Polymorphism in C#?

Object-oriented programming has mainly three pillars, Polymorphism is one of them after encapsulation and inheritance. It has special meaning - "many shapes" and has two aspects:
  • At run-time, derived class objects may be considered as base class objects in places such as method parameters and collections or arrays. When this polymorphism happens, declared and run-time types of object are different. For example,
    
        public class Shape
        {
        }
    
        public class Circle : Shape
        {
        }
        public class Rectangle : Shape
        {
        }
        var shapes = new List
            {
            new Rectangle(), new Triangle(), new Circle()
            };
    
  • Base classes may have virtual members which can be overridden by the derived class with their own definition and implementation. At the time of execution, When client code calls the method, the override method is executed because CLR looks up the run-time type of object rather than of the compile-time object. In your code you can cause a derived class method to be executed by calling a method of base class as below.
    
        A o1 = new A();
        o1.disp();
        B o2 = new B();
        o2.disp();
        A o3 = new B(); // here 
        o3.disp(); // derived class method will be executed by calling base class method
    
    
MSDN does not provide any information regarding static and dynamic polymorphism, rather than just two distinct aspects which are mentioned in above two points. Some authors consider function and operator overloading as static polymorphism, while some authors describe generic programming by parametric polymorphism So all these are different points of view of authors to explain the polymorphism. But MSDN considers dynamic polymorphism as a more convenient definition of Polymorphism.
For more about Polymorphism visit Polymorphism.

16. Can Abstract class have a constructor in C#? Below code will compile or not, or it will give any error in Error line 1 or 2.


class A
    {
       public virtual void display()
        {
            Console.WriteLine("A - display");
        }
        public virtual void disp()
        {
            Console.WriteLine("A - disp");
        }
    }
abstract class ab :A
    {
        public ab()
        { }
        public abstract override void display(); Error Line 1

        public sealed override void disp()  Error Line 2
        {
            Console.WriteLine("disp is sealed now.");
        }
    }

Solution: Abstract class can contain the constructor. Constructor is used to instantiate the class instance members in C#.
The above code will compile successfully. In C#, we can add Abstract and Sealed keywords with the override keyword.

17. What is the use of the sealed keyword in C#?

In C#, a sealed modifier is used to prevent your class from being inherited by other classes. When you want that other class should not inherit from your class then you can add a sealed modifier to it. You can create sealed classes in C# as below.

    class C {}
    sealed class D : C {} // other classes will not be able to inherit from class D.
You can use a sealed modifier to methods and properties in your class which are overriding methods and properties from base class. Using this way other classes will derive from your class and will not be able to override sealed methods and properties. For more visit C# sealed.

18. What is the difference between abstract and virtual keywords ?

Both virtual and abstract are the modifiers in C#. They have different use cases.

  • virtual keyword allows you to override any method, property, event declaration or indexer in derived class. It gives the capability to modify the implementation of the base class virtual member in derived class. Virtual members provide default implementation that you can modify in a derived class. When you invoke a virtual member, the run-time type of the object is considered for an overriding member.
    For more visit virtual C#.
  • abstract keyword indicates that the base class has incomplete implementation or something missing that you need to complete in derived class. You can use the abstract modifier with class, methods, properties, events and indexers.
    It is necessary to complete the implementation of abstract members of base class. Only an abstract class can contain abstract members and non-abstract members as well.
    For more visit abstract C#.

19. Explain string interpolation in C#.

In C#, String Interpolation provides the capability to create formatted strings with convenient and readable syntax. The $ special character allows you to create an interpolation string that might contain interpolation expressions. When the interpolation string resolves it replaces the interpolation expression with string representation of the interpolation item. String Interpolation is the feature of C# 6. Example:

        var name = "Microsoft";
        Console.WriteLine($"Hello {name}"); // O/P: Hello Microsoft
        
For more visit C# String Interpolation.

20. Explain about String Immutability in C#.

Once you create a String object in C#, It can not be modified. When you perform any operation like appending then you get a new instance of a modified String object instead of modifying the actual instance value. So String Objects are immutable in C#. If you are planning to perform many append operations on a string object then use StringBuilder class.
For more visit Immutable String in C#.

21. How to compare two String Objects in C#?

You should use the Compare method to determine the relationship of two strings in sorting order and if you want to test for equality of two strings then you should Instance Equals or static Equals method with a StringComparison type parameter.
For more about string operations visit String in C#.

21. What is nullable value type? How to read value from a nullable value type in C#?

22. What are the new features in C# 7.0?

To know more about C# 7.0 new features visit What's new in C# 7.3

23. What is Covariance and Contravariance in C#?

Fore more Covariance and Contravariance in C#

24. What points (related to try, catch and finally) you should keep in mind while implementing exception handling in C#?

25. What is Generics in C#? What are the benefits of Generics?

For more visit Generics in C#.

Memory Management in C# (26 - 31)

26. Explain Memory management (Heap vs Stack) in a C# Program.

For more visit Heaping vs Stacking in .NET and C# Memory Management.

29. How does Garbage Collection work in C#? Explain Generations.

For more visit Garbage Collection in C# and How GC manages memory?

30. What is using statement in C#?

In C#, All unmanaged resources and class libraries must implement the IDisposable or IAsyncDisposable interface.
The using statement ensures the correct use of IDisposable or IAsyncDisposable objects. When the object's lifetime is limited to a single method then you should use the 'using' statement to declare and instantiate disposable objects. An object declared inside a using statement can not be modified or re-assigned meaning it is read-only. It disposes the object in case of any exception or it's equivalent to try-finally implementation.
using statement example:

    string message=@"Hello I am good , first line
    How are you, second line
    I am fine third line";

    using var reader = new StringReader(message);
    string? line;
    do {
    line = reader.ReadLine();
    Console.WriteLine(line);
    } while(line != null);
For more visit using statement.

27. What is IDisposable Interface in C#? How to implement the dispose method?

For more visit Finalizer & Dispose.

28. Explain Dispose Pattern in C#.

31. What are the Finalizers in C#? Explain SupressFinalize() method.

For more visit Finalizers in C#

Collections in C# (32 - 40)

32. Explain different kinds of collections in C#.

33. What are the benefits of Generic Collections?

34. Explain algorithmic complexity of collections in C#.

37. Explain internal working of Dictionary or Hashtable.

For more visit Dictionary or Hashtable internal working Hashtable internal working.

35. When to use a thread-safe collection in C#?

36. How to perform comparisons and sorts within collections?

37. Explain Iterators in C#.

38. What is the difference between the Equality operator == and Equals() method in C#?

39. What is the use of new keyword apart from creating a new object in C#?

40. What are the extension methods in C#?

41. Explain the Lambda expressions in C#?

42. What are the anonymous methods in C#?

43. Explain Partial class and methods.

44. What are the different ways to pass parameters in C#?

45. How will you differentiate EXE and DLL files?

46. What is the DLL hell Problem?

47. Explain the concept of Parallel Processing, Concurrency, and Async Programming in .NET?

For more visit Parallel Processing, Concurrency, and Async Programming in C#.

48. How will you differentiate Thread vs Task?

48. What is volatile keyword in C#?

In C#, volatile keyword indicates that multiple executing threads which are executing at the same time can modify the value of a field. The fields which are declared volatile are observed by all the threads for volatile writes by any other thread in the same order in which it was performed. All reads and writes to memory locations of volatile fields may be rearranged by the compiler, the runtime and even hardware for performance reasons. For more visit C# volatile.

49. What is async and await in C#?

Both async & await keywords are used to implement asynchronous operations in C#. These operations could be either I/O bound (such as web service taking time to download some content or file) or CPU bound (any expensive calculation by CPU).
You can mark a method, lambda expression or anonymous method as async. Async method should have at least one await statement to perform operation asynchronously and it returns Task means - the ongoing work. When the control reaches the awaited expression, the method is suspended until the task gets completed because we are waiting for the result of the awaited task.

    public async Task<int> ExampleMethodAsync()
    {
    //...
    string contents = await httpClient.GetStringAsync(requestUrl);
    }
For more about Asynchronous programming visit Asynchronous programming with async and await and async await C#.

50. How to handle exceptions in Async methods?

For more visit Exceptions in async methods.

50. Explain C# 6.0 new features.

C# 6.0 has many new features. For more visit What's new in C# 6.0

51. What is Deep copy and Shallow copy?

For more visit Cloning;

52. What is the use of yield keywords in C#?

53. How User-defined conversions work in C#?

54. Differentiate Action vs Func in C#.


    
        class Test
        {
        // Func Example
        public string CreateNamefromName1()
        {
        return CreateName(GetName1);
        }
        public string CreateNameFromName2()
        {
        return CreateName(GetName2);
        }
        private string CreateName(Func<string, string, string> createName)
            {
            var name1 = "hello";
            var name2 = "testing";
            return createName(name1, name2);
            }

        private string GetName1(string arg1, string arg2) => $"{arg1}-{arg2}";
        private string GetName2(string arg1, string arg2) => $"{arg1}::{arg2}";

         }
    

55. Explain the use of below interfaces in C#?

C# Coding Interview Questions

49. Print the output of the below program? Error Line will throw any error in below code?


  class A
    {
       public virtual void display()
        { Console.WriteLine("A - display method"); }
    }
    class B:A
    {
        public override void display()
        { Console.WriteLine("B - display method"); }
    }
    class Test
    {
        static void Main()
        {
            A obj = new A();
            obj.display();

            A obj1 = new B();
            obj1.display();

            B o = new B();
            o.display();
            // B ob = new A();  Error Line
            Console.ReadLine();
        }
    }

Output: 'Error Line' will throw error - "Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists (are you missing a cast?)".
Output will be as below.
A - display method
B - display method
B - display method

55. What will be the output here? or will it throw any error?


    public void display()

    {
    int x = 0;
    int y = 10;
    try
    {
    int z = y / x;
    }
    catch (Exception)
    {
    throw;
    }
    catch (DivideByZeroException)
    {
    throw;
    }
    finally
    {
    }

    }

56. Print the output of this program?


    int a = 0;
    try
    {
    int x = 4;
    int y ;
    try
    {
    y = x / a;
    }
    catch (Exception e)
    {
    Console.WriteLine("inner ex");
    //throw;   // Line 1
    //throw e;   // Line 2
    //throw new Exception("divide by 0");  // Line 3
    }

    }
    catch (Exception ex)
    {
    Console.WriteLine("outer ex");
    throw ex;
    }

Let's see the output:
  • Output will be - "inner ex" as we are not throwing anything from the inner catch block, so the outer catch block will not execute.
  • If we uncomment 'Line 1' then output will be - "inner ex" and "outer ex" and outer catch will throw an exception.
  • If we uncomment 'Line 2' then output will be the same - "inner ex" and "outer ex" and outer catch will throw an exception.
  • If we uncomment 'Line 3' then output will be - "inner ex" and "outer ex" but the exception message in outer catch will be different, overridden by a throw message from inner catch block.

Some General Interview Questions for C#

1. How much will you rate yourself in C#?

When you attend an interview, Interviewer may ask you to rate yourself in a specific Technology like C#, So It's depend on your knowledge and work experience in C#.

2. What challenges did you face while working on C#?

This question may be specific to your technology and completely depends on your past work experience. So you need to just explain the challenges you faced related to C# in your Project.

3. What was your role in the last Project related to C#?

It's based on your role and responsibilities assigned to you and what functionality you implemented using C# in your project. This question is generally asked in every interview.

4. How much experience do you have in C#?

Here you can tell about your overall work experience on C#.

5. Have you done any C# Certification or Training?

It depends on the candidate whether you have done any C# training or certification. Certifications or training are not essential but good to have.

Conclusion

We have covered some frequently asked C# Interview Questions and Answers to help you for your Interview. All these Essential C# Interview Questions are targeted for mid level of experienced Professionals and freshers.
While attending any C# Interview if you face any difficulty to answer any question please write to us at info@qfles.com. Our IT Expert team will find the best answer and will update on the portal. In case we find any new C# questions, we will update the same here.