×

Top 20 C# Interview Questions and Answers

Shailendra Chauhan  Print   18 min read  
29 Apr 2022
 
47.6K Views

C# is the most popular and widely used programming language for developing web applications, desktop applications, and mobile apps. This article contains the top 20 C# interview questions and answers, in order to prepare you for the interview.

  1. What is C#?

    C# pronounced as "See Sharp". It is an object-oriented programing language developed by Microsoft, which runs under the .NET platform. Its syntaxes are similar to C++ or Java. The most recent version of C# is 7.3 which is introduced with Visual Studio 2017 update 15.7. C# is widely used for developing web applications, desktop applications, mobile apps, and games, etc. Now, C# can be run on Mac, Linux/Unix, and Windows using .NET Core.

    C# is one of the simplest, modern, absolute, and widely used object-oriented programming languages. The primary purpose of using the C# language was to develop a programming language that is not just only easy the learnings but also supports the modern-day functionalities for the variety of software development. And if we look at the global history of the software programming languages and their certain features, each programming language was designed for a certain purpose to solve a specific need of the tech industry at that time.

  2. Explain the evolution history of C#?

    The evolution history of C# is given below:

    Evolution history of C#
  3. What features are added to different versions of C#?

    The following features are added to different versions of C#:

    C# 1.0

    • Managed Code

    • IDE - Visual Studio .NET 2002, 2003

    • .NET Framework - 1.0, 1.1

    C# 2.0

    • Generics

    • Static Classes

    • Partial types

    • Anonymous methods

    • Iterators

    • Nullable types

    • Asymmetric Property and Indexer Accessors

    • Delegate Inference

    • Covariance and Contra-variance

    • .NET Framework - 2.0

    C# 3.0

    • Implicit types (var)

    • Partial Methods

    • Object and collection initializers

    • Auto-Implemented properties

    • Anonymous types

    • Extension methods

    • Query expressions

    • Lambda expressions

    • Expression trees

    • IDE - Visual Studio 2008

    • .NET Framework - 3.5

    C# 4.0

    • Dynamic binding

    • Named arguments

    • Generic Covariance and Contra-variance

    • COM Interop

    • IDE -Visual Studio 2010

    • .NET Framework - 4.0

    C# 5.0

    • Asynchronous methods

    • Caller info attributes

    • IDE - Visual Studio 2012, 2013

    • .NET Framework - 4.5, 4.5.1

    C# 6.0

    • Auto Property Initializer

    • Primary Constructors

    • Dictionary Initializer

    • Declaration Expressions

    • Static Using

    • await inside catch block

    • Exception Filters

    • Null-Conditional Operator

    • IDE - Visual Studio 2015

    • .NET Framework - 4.6

    C# 7.0

    • Local Functions

    • Literal improvements

    • Digit Separators

    • Pattern matching

    • ref returns and ref Locals

    • Throw Expressions

    • Expression Bodied Members

    • Deconstruction

    • IDE - Visual Studio 2017

  4. What is Asynchronous Method?

    In C# 5.0 two keywords async and await are introduced which allow you to write asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0, for writing asynchronous code, you need to define callbacks to capture what happens after an asynchronous process finishes. These keywords are used in a combination of each other and an await operator is applied to a one or more than one expression of an async method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method.

     public async Task<IEnumerable<Product>> GetProductList()
     {
     HttpClient client = new HttpClient();
     Uri address = new Uri("http://dotnettricks.com/");
     client.BaseAddress = address;
     
     HttpResponseMessage response = await client.GetAsync("myservice/product/ProductList");
     
     if (response.IsSuccessStatusCode)
     {
     var list = await response.Content.ReadAsAsync<IEnumerable<Product>>();
     return list;
     }
     else
     {
     return null;
     }
     }
     
  5. Explain the C# code execution process?

    C# code execution life cycle diagram is shown as follows :

    C# life cycle process diagram
  6. What are the advantages of C# over Java?

    The advantage of C# over java is given below :

    • C# offers cross-language interoperability or mixed language programming (Java lacking).

    • C#directly supports the Windows operating system (Java lacking).

    • C# is component-oriented language integrated support for the writing of software support.

    • C# support pointer as unsafe (Java lacking it).

      The java compiler and the C# compilers both of them generate an intermediate or the compiled language code after end compilation. The C# compiler generally generates the code of  Microsoft Intermediate Language, and the Java compiler generates Java bytecode after the compilation cycle.

  7. What is Datatype?

    Data Type refers to the type of data that can be stored in a variable. It also specifies how much memory would be allocated to a variable and the operations that can be performed on that variable. C# is rich in data type which is broadly divided into two categories.

    • Value Type

    • Reference Type

  8. What is the difference between value type and reference type?

    Value Type: A value type variable stores actual values. Values types are of two types - built-in and user-defined. Value types are stored in a stack and derived from System.ValueType class.

     
     int x = 10;
     char ch = 'a';
     
    C# data types

    Reference Type: A reference type variable stores a reference to the actual value. Typically, a reference type contains a pointer to another memory location that stores the actual data. Reference types are of two types - built-in and user-defined. Reference types are stored in a heap and derived from System. Object class.

  9. What are Nullable types?

    Value types that can accept a normal value or a null value are referred to as Nullable types. These are instances of the Nullable struct. For example, A Nullable<bool> is pronounced as "Nullable of bool" and can have the values true, false, or null. Nullable types can also be defined using the ? type modifier. This token is placed immediately after the value type is defined as nullable.

     //assigning normal value
     Nullable<bool> flag = true;
     //Or You can also define as
     bool? flag = true;
     
     //assigning normal value
     Nullable<int> x = 20;
     //Or You can also define as
     int? x = 20;
     

    Note

    You should not declare a string as nullable since it is implicitly nullable. Hence, declaring a string type like string? firstName causes a compile-time error.

  10. What is Operator in C#?

    The Operator is called the null coalescing operator. It is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand.

    Operators in C# are a kind of special symbol that performs certain actions on the different operands. If we consider the concept of mathematics, then the plus symbol or operator does the summation of the left and right numbers or the series of numbers. And the same way, C# also includes various sets of operators for different types of operations such as summation, multiplication, division, and so on.

    Below is the example where the operator "??" is used along with the two operands like "x" and "y" and in the same way we can use another operator in C#.

     int? x = null;
     int y = -1;
     
     // when x is null, z = y
     // when x is not null, z = x
     int z = x ?? y; // where x and y are left and right operand
     
  11. What is the dynamic type in C#?

    The dynamic type was introduced in C# 4.0. Dynamic type variables are declared using the "dynamic" keyword. A dynamic type variable bypasses the compile-time type checking and its operations are resolved at run time. In dynamic type, if the operations are not valid then the exception would be thrown at run time, not at compile time.

    We can define the dynamic data type using the reserved keyword called “dynamic" in our codebase. The variable of the dynamic data type would be initialized by the specific type of the data such as int, string, float, or the object. The dynamic variables can be used to create the properties and it will return the values from a method.

    Below is the example where the dynamic type is created using the "dynamic" keyword 

     class Program
     {
     public static void Main()
     {
     dynamic d = 1; //assigning integer
     Console.WriteLine(d);
     
     d = "Hi Dynamic"; //assigning string to the same variable d
     Console.WriteLine(d);
     
     d = TestData(); //assigning method result to the same variable d
     Console.WriteLine(d);
     
     // You can call anything on a dynamic variable,
     // but it may result in a runtime error
     Console.WriteLine(d.Error);
     }
     
     public static double TestData()
     {
     return 12.80;
     }
     }
     
     /* Output
     
     10
     Hi Dynamic
     12.80
     RuntimeBinderException was unhandled, 'double' does not contain a definition for 'Error'
     */
     
  12. What are the differences between ref and out parameters?

    Ref - The ref keyword makes an argument (data) to be passed by reference to the corresponding parameter. Hence, when the value of the parameter is changed in the method, it gets reflected in the calling method.

    Key Points

    • The Passing argument must be initialized before passing to the method using the ref keyword.

    • A Property cannot be passed as a ref parameter since internally property is a function.

    Out – The out keyword also makes an argument (data) to be passed by reference to the corresponding parameter, but that argument can be passed without assigning any value to it.

    Key Points

    • The passing argument must be initialized in the passed method before it returns back to the calling method.

    • Also, a Property cannot be passed as an out parameter since an internal property is a function.

    For example, A program uses the ref and out keyword as a method argument.

     public class MyClass
     {
     public static void Main()
     {
     int arg1 = 0; //must be initialized 
     int arg2;
     
     MyMethod1(ref arg1);
     Console.WriteLine(arg1); // Now 2!
     
     MyMethod2(out arg2);
     Console.WriteLine(arg2); // Now 3!
     }
     
     static void MyMethod1(ref int param1)
     {
     param1 = 1; //initialization is optional
     }
     static void MyMethod2(out int param2)
     {
     param2 = 2; //must be initialized 
     }
     }
     
     /* Output
     1
     2
     */
     
  13. What do you mean by Class?

    A Class is a user-defined data structure that contains data members (fields, properties, events, and indexer), member function, and nested class type. Basically, a class is :

    • A user-defined data type.

    • A reference type.

    • A tag or template for an object.

     class Book
     {
     //Attributes
     int BookId;
     string Title;
     string Author;
     string Subject;
     double Price;
     
     //Parametrized constructor to set book details
     public Book(int bookId, string title, string author, string subject, double price)
     {
     BookId = bookId;
     Title = title;
     Author = author;
     Subject = subject;
     Price = price;
     }
     
     //Behaviours
     public void showDetails()
     {
     Console.WriteLine("\n########## Book Details ##########");
     
     Console.WriteLine("BookId :{0}", BookId);
     Console.WriteLine("Title : {0}", Title);
     Console.WriteLine("Author : {0}", Author);
     Console.WriteLine("Subject : {0}", Subject);
     Console.WriteLine("Price : {0}", Price);
     }
     }
     
     public class Program
     {
     public static void Main(string[] args)
     {
     //object creation and initialization
     Book objBook1 = new Book(1, "ASP.Net Interview Questions & Answers", "Shailendra Chauhan", ".NET Interview", 500);
     Book objBook2 = new Book(2, "C# Interview Questions & Answers", "Shailendra Chauhan", ".NET Interview", 400);
     
     //calling class
     objBook1.showDetails();
     objBook2.showDetails();
     
     Console.ReadKey();
     }
     }
     
     /* Output
     
     ########## Book Details ##########
     BookId :1
     Title : ASP.Net Interview Questions & Answers
     Author : Shailendra Chauhan
     Subject : .NET Interview
     Price : 500
     
     ########## Book Details ##########
     BookId :2
     Title : C# Interview Questions & Answers
     Author : Shailendra Chauhan
     Subject : .NET Interview
     Price : 400
     */
     
  14. What do you mean by Object?

    An object is a representative of the class and is responsible for memory allocation of its data members and member functions. An object is a real-world entity having attributes (data members) and behaviors (member functions).

    For example, a student object can have attributes name, address, and contact number. It performs activities attending class, giving exams, etc.

  15. What is Constructor?

    A constructor is a special type of function/method which has the same name as its class. The constructor is invoked whenever an object of a class is created. It is called a constructor since it constructs the values of the class data members.

    Key points

    • It is a special function/method because its name is the same as the class.

    • It can be overloaded the same as normal methods.

    • It is automatically invoked as soon as the object of the class is created.

    • It does not return a value, not even a void type.

  16. What are the different types of constructors?

    There are three types of the constructor – default constructor, parameterized constructor, and copy constructor. But C# does not support copy constructor.

    1. Default Constructor

      A default constructor has no parameter. When a class has no constructor, a default constructor is served by the compiler to that class.

    2. Parameterized Constructor

      The parameterized constructor has one or more arguments and is used to assign values to instance variables of the class.

       class Example
       {
       double num1, num2;
       
       #region Constructor Overloading
       
       //Default Constructor
       public Example()
       {
       Console.WriteLine("This is a default constructor!");
       }
       
       //Parameterized Constructor
       public Example(int a, int b)
       {
       num1 = a;
       num2 = b;
       Console.WriteLine("This is a parameterized constructor!");
       }
       
       //Parameterized Constructor
       public Example(double a, double b)
       {
       num1 = a;
       num2 = b;
       Console.WriteLine("This is a parameterized constructor!");
       }
       #endregion
       
       public void ShowResult()
       {
       double result = num1 + num2;
       Console.WriteLine("Result: {0}", result);
       }
       }
       
       class Program
       {
       static void Main()
       {
       Example obj1 = new Example(); //default constructor called
       Example obj2 = new Example(4, 5); //parameterized constructor called
       Example obj3 = new Example(4.2, 5.2); //parameterized constructor called
       
       obj2.ShowResult();
       obj3.ShowResult();
       Console.Read();
       }
       }
       
       /* OutPut 
       This is a default constructor!
       This is a parameterized constructor!
       This is a parameterized constructor!
       Result: 9
       Result: 9.4
       */
       
    3. Copy Constructor

      This constructor is used to copy the entire values of an object to another object. But C# does not support copy constructor.

  17. What is Destructor?

    The destructor is a special type member function/method which has the same name as its class name preceded by a tilde (~) sign. The destructor is used to release unmanaged resources allocated by the object. It is called automatically before an object is destroyed. It cannot be called explicitly. A class can have only one destructor.

    class Example
    {
     public Example()
     {
     Console.WriteLine("Constructor called");
     }
    
     //destructor
     ~Example()
     {
     Console.WriteLine("Destructor called to destroy the instance");
     }
    }
    
    class Program
    {
     static void Main()
     {
     Example T = new Example();
     GC.Collect();
     }
    }
    /*Output 
     
    Constructor called.
    Destructor called to destroy the instance
    
    */
    
  18. What is finalize () method?

    Finalize method is used to free unmanaged resources like files, database connections, COM, etc. held by an object before that object is destroyed. Internally, it is called by Garbage Collector and cannot be called by user code. Finalize method belongs to the Object class in C#.

    You should implement it when you have unmanaged resources in your code and want to make sure that these resources are freed when the Garbage collection happens.

    // Implementing Finalize method
    class Example
    {
     public Example()
     {
     Console.WriteLine("Constructor called");
     }
    
     //At runtime C# destructor is automatically Converted to Finalize method.
     ~Example()
     {
     //TO DO: clean up unmanaged objects
     }
    }
    
  19. What are Generics in C#?

    Generics were introduced in C# 2.0. Generics allow you to define type-safe classes, interfaces, methods, events, delegates, and generic collections without compromising type safety, performance, or productivity. In generics, a generic type parameter is supplied between the open (<) and close (>) brackets and which makes it strongly typed collections i.e. generics collections contain only similar types of objects.

    C# allows us to define the generics in a different way such as the generic classes, abstract classes, static methods, interfaces, fields, methods, properties, events, delegates, and the set of operators using the "type" parameter and without specifying any type of data type. The "type" parameter is a placeholder for a particular type specified when creating an instance of the generic type. Normally, a generic type can be declared by specifying the type parameter in an angle brackets followed by the type name i.e. "TypeName<T>" where the "T" is a type parameter.

  20. What is Multithreading in C#?

    Multithreading allows you to perform concurrent processing so that you can do more than one operation at a time. The .NET Framework System. The threading namespace is used to perform threading in C#.

    The Multithreading in C# is one of the core features provided by the operating system that enables our application to have more than one execution path or a concurrent path at the same time. Apart from that, the multithreaded programming feature requires a multitasking operating system.

    Multithreading in C#

    For example, you can use one thread to monitor input from the user, a second thread to perform background tasks, a third thread to process user input, and a fourth thread to show the output of the third thread processing.

Summary

I hope these questions and answers will help you to crack your C# interview. These interview questions have been taken from our newly released eBook C# Interview Questions & Answers. This book contains more than 140+ C# interview questions.

This eBook has been written to make you confident in C# with a solid foundation. Also, this will help you to turn your programming into your profession. It's would be equally helpful in your real projects or to crack your C# Interview.

Buy this eBook at a Discounted Price!

 C# Interview Questions & Answers eBook
Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

Accept cookies & close this