Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Basic C# Interview Questions
2.1.
1. What is C#?
2.2.
2. What are the features of C#?
2.3.
3. What is an object in C#?
2.4.
4. What is a class in C#?
2.5.
5. What is inheritance in C#?
2.6.
6. What is an interface in C#?
2.7.
7. What is an abstract class in C#?
2.8.
C#
2.9.
8. What is a constructor in C#?
2.10.
9. What is a delegate in C#?
2.11.
10. Define arrays with the help of an example in C#.
2.12.
C#
2.13.
11. How is C# different from C?
2.14.
12. What is Garbage Collection in C#?
2.15.
13. What are the types of classes in C#?
2.16.
14. What is Common Language Runtime?
2.17.
15. What is the difference between an Array and ArrayList in C#?
3.
Medium Level C# Interview Question
3.1.
16. What is the difference between a struct and a class in C#?
3.2.
17. What is a lambda expression in C#?
3.3.
18. What is the difference between an abstract class and an interface in C#?
3.4.
19. What is LINQ in C#?
3.5.
20. Differentiate between a stack and a queue in C#?
3.6.
21. What is the difference between a value type and a reference type in C#?
3.7.
22. What is the difference between null and non-nullable types in C#?
3.8.
23. Which are the access modifiers available in C#?
3.9.
24. What is the difference between dispose() and finalize() methods in C#?
3.10.
25. What is the difference between method overloading and method overriding in C#?
3.11.
C#
3.12.
26. What are the differences between ref and out keywords?
3.13.
27. What are extension methods in C#?
3.14.
28. Does C# support multiple inheritances?
3.15.
29. What are the different types of comments in C#?
3.16.
30. List the steps of compiling a C# code.
4.
Advanced Level C# Interview Questions
4.1.
31. What are generics in C#.NET?
4.2.
32. Mention different ways in which a method can be overloaded.
4.3.
C#
4.4.
33. Differentiate between early and late binding in C#.
4.5.
34. What are partial classes, and what is their use in C#?
4.6.
35. How would you force Garbage Collection?
4.7.
36. How would you create a responsive UI without impacting users in C#?
4.8.
37. What is the difference between a string and a StringBuilder in C#?
4.9.
C#
4.10.
C#
4.11.
38. Why is the singleton pattern referred to as an anti-pattern in C#?
4.12.
39. What is a virtual method in C#?
4.13.
40. List the features of read-only variables in C#.
4.14.
41. What are stream reader and stream writer classes in C#?
4.15.
42. What do you mean by boxing and unboxing in C#?
4.16.
43. Differentiate between Task and Thread in C#.
4.17.
44. What is finally block in C#?
4.18.
45. How do you implement exception handling in C#?
4.19.
46. What are dynamic type variables in C#?
4.20.
47. Explain Anonymous types in C#.
4.21.
48. How is encapsulation implemented in C#?
4.22.
49. Differentiate between constant and readonly in C#.
4.23.
50. What is the use of the yield keyword in C#?
5.
Frequently Asked Questions
5.1.
What is C# and why C#?
5.2.
What is the main function of C#?
5.3.
Is C# and .NET same?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Top 50 C# Interview Questions and Answers (2023)

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

C# is an object-oriented programming language used to develop web apps, websites, desktop apps, and many more applications. It allows code reuse and duplication of code.

c# interview questions

In this article, we will go through some frequently asked C# Interview questions and answers.

Basic C# Interview Questions

Let us go through some easy level C# interview questions and answers.

1. What is C#?

Ans: C# is a modern general-purpose programming language developed by Microsoft. It is used to develop various applications, including Windows desktop applications, mobile applications, and web apps. It runs on .Net framework. C# is mainly a type-safe language, ensuring the internal consistency of each type. For example, C# restricts you from treating a string type like an integer type when you deal with it.

2. What are the features of C#?

Ans: Some features of C# are mentioned below:

  • Strong type checking.
  • Automatic memory management.
  • Object-oriented programming.
  • Interoperability with other languages.
  • Component-based architecture.
  • Delegate type for events and callbacks.

3. What is an object in C#?

Ans: An object in C# is an instance of a class. It holds the values of the properties defined in the class and can access the methods of the class. An object is created using the "new" operator followed by the name of the class. The values of the object's properties can be accessed and modified using dot notation. 

Objects are used to encapsulate data and behavior in a single unit, making it easier to organize and manipulate code.

4. What is a class in C#?

Ans: A class in C# is a blueprint or a template that defines the properties, fields, and methods that an object of that class should have. A class is a fundamental building block in oops and encapsulates data and behavior.

Syntax

class class_name
{ 
// Fields
// methods

}

 

For example, you can create a class named "Person" that has properties like "Name" and "DOB" and methods like "Speak" and "Walk." When you create an instance of the "Person" class, you have an object that has the properties and methods defined in the "Person" class.

5. What is inheritance in C#?

Ans: Inheritance in C# is an oop feature that allows a class to inherit properties and methods from a base class. This enhances code reusability and helps to reduce duplication of code. The derived class inherits the base class members and can also add its members, making it a specialized version of the base class. The parent class is the class being inherited by the derived class.

Syntax

class derived-class : base-class  
{  
   // Code

} 

 

Inheritance promotes code modularity and enables the creation of new classes built upon existing ones.

6. What is an interface in C#?

Ans: An interface in C# is a blueprint that defines a set of methods and properties that a class must implement. Interfaces provide a way to specify the contract that a class must follow and allow for multiple inheritances in C#. They are used to define a common behavior that multiple classes can implement, promoting code reuse and making it easier to maintain and update the code. 

All the members of the interface are public and abstract by default.

Interfaces are declared using the "interface" keyword in C# and can be implemented by classes using the "implements" keyword, providing total abstraction.

The syntax to declare the interface.

interface <interfaceName >
{
    // code

}

 

The syntax to implement the interface.

class class_name : interface_name

 

7. What is an abstract class in C#?

Ans: An abstract class in C# is a class that cannot be instantiated on its own but is intended to be used as a base class for other classes. An abstract class is declared using the "abstract" keyword and is used to provide a common implementation for its derived classes. An abstract class can have methods, constructors, or destructors. 

Example

  • C#

C#

using System;

namespace MyApplication {
  
 abstract class Person
 {
  
   public abstract void movement();
 
   public void walk()
   {
     Console.WriteLine("Walking");
   }
 }

 class Child : Person
 {
   public override void movement()
   {
   
     Console.WriteLine("The child is walking");
   }
 }

 class Example
 {
   static void Main(string[] args)
   {
     Child obj = new Child(); 
     obj.movement();
     obj.walk();
   }
 }
}

 

Output

The child is walking
Walking

 

It allows for code reuse and can contain abstract methods, which are methods that do not have a concrete implementation and must be overridden in the derived classes.

8. What is a constructor in C#?

Ans:  A constructor in C# is a special method that is called when an object of a class is created. It is used to initialize the properties of the object and perform any other necessary setup. A constructor has the same name as the class and does not have a return type. Two types of constructors in C# are:

  • Default constructor.
  • Parameterized constructor.

Syntax

class Example
{   
  
  // Constructor
  public Example() {}
}

// Object of Example class
Example obj = new Example();

 

9. What is a delegate in C#?

Ans: A delegate in C# is a type that represents a method with a specific signature. It acts as a reference to a method and can be passed as a parameter to another method. Delegates are used to implement events and callbacks in C# and provide a way to pass methods as arguments to other methods, allowing for more dynamic and flexible code. 

10. Define arrays with the help of an example in C#.

Ans: Array data structure groups similar elements under a single block where memory allocation of the array elements is dynamic. The members in the array are linearly and can be accessed using an index value starting from 0. This means that the first element of the array is at the 0th position, and the last element of the array will be the total number of elements - 1.

basic C# interview question

There are three types of arrays in C#:

  • Single Dimensional.
  • Multi-Dimensional.
  • Jagged Array.
     

Syntax: 

< Data Type > [ ] < Array_Name >

 

Example

  • C#

C#

using System;

namespace MyApplication
{
 class Example
 {
   static void Main(string[] args)
   {
     int[] numbers = {1, 2, 3, 5, 8};
     Console.WriteLine(numbers[0]);
     string[] colors = {"Blue", "White", "Red", "Black"};
     Console.WriteLine(colors[3]);
   }
 }
}

 

Output

1
Black

 

Explanation:

In the above program, the first array of "numbers" is of int type storing five numbers, and the value of element at index 0 in that array is printed. The second array, "colors," of string data type storing strings, and the value of the element at index 3 in the colors array is printed, i.e., Black.

11. How is C# different from C?

C# is a modern, object-oriented programming language that was designed by Microsoft specifically for the .NET platform. Compared to C, C# includes many additional features such as garbage collection, automatic memory management, a unified type system, strong type checking, and a rich set of standard libraries. Additionally, C# supports modern language features such as lambdas, LINQ, and async/await, which are not available in C. While C is a procedural language, C# is more of an object-oriented language.

12. What is Garbage Collection in C#?

In C#, Garbage Collection is a process of management of memory used by an application. When an application creates an object, it is allocated memory from the heap. When the object is no longer needed, the memory it occupies becomes available for reuse. Garbage Collection is the process by which the .NET runtime automatically frees up this memory when it is no longer in use.

We do not have to explicitly free the memory used by an object once it is no longer needed. The Garbage Collector periodically scans the heap to determine which objects are no longer being used by the application and can be safely removed. The Garbage Collector is responsible for reclaiming the memory used by those unused objects, making it available for reuse by the application.

13. What are the types of classes in C#?

There are several types of classes in C#. Let us look at some of them:

  1. Regular Class: These are the most common type of classes in C#. They can contain fields, properties, methods, events, and other members. You can use regular classes to define objects that represent real-world entities or abstract concepts.
     
  2. Partial class: These are classes that are split into multiple files. Each file contains a portion of the class definition, and the compiler combines them into a single class.
     
  3. Abstract Class: These are classes that cannot be instantiated directly. Instead, they are designed to be inherited by other classes.
     
  4. Sealed Class: These are classes that cannot be inherited by other classes. Sealed classes are often used to prevent unintended modification of a class, or to improve performance by allowing the compiler to optimize the code.
     
  5. Nested Class: These are classes that are defined within another class. Nested classes can be either static or non-static, and can be used to encapsulate functionality that is only relevant to the containing class.
     
  6. Static Class: These are classes that contain only static members, such as fields, methods, and properties.

14. What is Common Language Runtime?

The Common Language Runtime (CLR), is one of the components of the .NET framework. It manages the execution of the .NET programs written in languages like C#. The CLR provides a number of services that are essential for .NET programs to run correctly, including memory management, security, exception handling, and thread management. The CLR also provides just-in-time (JIT) compilation, which compiles the CIL code into machine code at runtime, allowing the code to be optimized for the specific hardware and operating system.

15. What is the difference between an Array and ArrayList in C#?

Array

ArrayList

The type of element in an array must be specified at the time of creation of the array i.e., they are statically typed. ArrayLists are dynamically typed which means that we can store elements of any type.
Arrays have a fixed size and cannot be changed once the array is created. ArrayLists can resize themselves and are more flexible than arrays.
Arrays are generally faster because if fixed size. ArrayLists are slower as they require more memory and performance overhead.
Arrays are created using [] within which the size is specified. ArrayLists can be created using ArrayList classand the initial size can be specified.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Medium Level C# Interview Question

Let's begin with some medium-level C# Interview questions and answers.

16. What is the difference between a struct and a class in C#?

Ans: The difference between a struct and class in C# is:

Struct Class
Structs are value types, meaning that when you assign a struct to a variable, you create a copy of the struct in memory. Classes are reference types, meaning that when you assign a class to a variable, you create a reference to an object stored elsewhere in memory.
Structs are stored on the stack. Classes are stored on the heap.
Structs cannot have destructors. Classes can have destructors.
Struct does not support the protected modifier. The class supports protected modifiers.

17. What is a lambda expression in C#?

Ans: A lambda expression in C# is a shorthand syntax for creating anonymous functions. It allows you to define a method in place without declaring a separate delegate or named method. A lambda expression can be assigned to a delegate type or passed as a parameter to a method that expects a delegate. 

Two types of lambda expressions are:

a. Expression lambda

input => expression;

 

b. Statement lambda

input => { statements };

 

Example

using System;
public class Example
{
    public static void Main(string[] args)
    {
        List<int> n = new List<int> {5, 6, 4, 1, 9, 2};


var c = n.Count( a =>
                {
                    return a == 4;
                });


Console.WriteLine(c);
    }
}

 

Explanation:

The lambda expression in the above program is inside the Count query - a => { return a== 4; }. The Count counts the number of items and will return a boolean as output.

Lambda expressions provide a more concise and readable way to write inline code and can be used to simplify event handling, iteration, and LINQ (Language Integrated Query) operations.

 

18. What is the difference between an abstract class and an interface in C#?

Ans: The difference between a abstract class and interface in C# is:

Abstract class

Interface

An abstract class in C# can contain both abstract and concrete methods and properties, and its derived classes can override its abstract methods to provide their own implementation. An interface in C# only defines a set of methods and properties that a class must implement without providing any implementation.
It contains different types of access modifiers. It contains only public access modifiers.
The performance is fast. The performance is slow.
Abstract class can be implemented using the “:” keyword. Interface can be implemented using “:” and “,” keywords.
The “abstract” keyword is used to declare the abstract class. The “interface” keyword is used to declare the interface.

Example:

public abstract class Person{

public abstract void walk();

}

 

Example:

public interface Person{

void walk();

}

 

19. What is LINQ in C#?

Ans: LINQ (Language Integrated Query) is a feature in C# that allows you to write SQL-like queries against various data sources, including arrays, lists, and databases. LINQ provides a unified way to access and manipulate data, making it easier to write and maintain code that works with different types of data sources.

20. Differentiate between a stack and a queue in C#?

Ans: The difference between a stack and a queue in C# is:

Stack

Queue

A stack is a last-in-first-out (LIFO) data structure, meaning that the last item added to the stack will be the first item removed. A queue is a first-in-first-out (FIFO) data structure, meaning that the first item added to the queue will be the first item removed.
Only one pointer is used to access the elements of the stack. Two pointers are used to access the elements of the queue.
The push operation is used to insert an element in the stack. The enqueue operation is used to insert an element in the queue.
The pop operation is used to delete an element in the stack. The dequeue operation is used to delete an element in the queue.

21. What is the difference between a value type and a reference type in C#?

Ans: In C#, value types directly store their data, while reference types store a reference to an object in memory. When a value type is assigned to a variable, a new instance of the value type is created in memory, containing a copy of the data. 

Some of the value data types are:

  • byte.
  • int.
  • char.
  • long.
  • short.

Example:

There is a variable of integer type x = 50. The System stores 50 at some hypothetical location in the memory space allocated for the integer variable x.

On the other hand, reference types store a reference to the memory location where the object is stored rather than storing the data directly. This means that when a reference type is assigned to a variable, it is a reference to the same object in memory rather than a new instance.

Some of the referenced data types are:

  • Arrays.
  • Class.
  • String.
  • Delegate.

 

Example:

Suppose str = “Hello Ninjas”, the system selects the hypothetical location in memory for the variable str. The value of the str is the memory address of the actual location of the data. Hence the reference type stores the address of the location of the actual value. 

22. What is the difference between null and non-nullable types in C#?

Ans: A nullable type in C# can be assigned a value of either its type or null, while a non-nullable type cannot be assigned a value of null and must always have a value of its type. Nullable types are useful when a value may not always be present, while non-nullable types are used for values that must always have a value.

23. Which are the access modifiers available in C#?

Ans: In C#, there are five access modifiers that control the accessibility of classes, members, and other elements in a program:

  1. public: The member or class is accessible from anywhere in the program.
     
  2. private: The member or class is accessible only within the same class.
     
  3. protected: The member or class is accessible within the same class and in derived classes.
     
  4. internal: The member or class is accessible within the same assembly (a unit of deployment in . NET).
     
  5. protected internal: The member or class is accessible within the same assembly and in derived classes.

24. What is the difference between dispose() and finalize() methods in C#?

Ans: The Dispose method in C# is an explicit method that the user can call to release resources held by an object. The Finalize method is an implicit method that the garbage collector automatically calls to release resources when an object is no longer needed. The Dispose method is preferred over the Finalize method as it allows for more immediate and efficient resource management.

25. What is the difference between method overloading and method overriding in C#?

Ans: In C# method overloading involves creating multiple methods with the same name but different parameters in the same class. Method overriding involves creating a method in a derived class with the same name, return type, and parameters as a method in the base class. 

Overloading allows for multiple methods with the same name to perform different operations. In contrast, overriding allows for a derived class to provide its own implementation of a method in the base class.

 

Example of Method Overloading:

using System;  
namespace Application  
{  
    class Overloading  
    {  
        public int mul(int x, int y)  
        {  
            return (x*y);  
        }  
        public int mul(int x, int y, int z)  
        {  
            return (x*y*z);  
        }  
 
         
        static void Main(string[] args)  
        {  
            Overloading obj = new Overloading();  
            Console.WriteLine("First method : " + obj.mul(1, 2));  
            Console.WriteLine("Second method :" + obj.mul(5, 2, 5));  
            
            Console.ReadLine();  
        }  
    }  
}  

 

Output

First method : 2

Second method :50

 

Explanation:

In the above program, we use two methods with the same name but with different parameters. So the compiler automatically calls the method with two integers parameters when you call mul(1, 2). While the same with the other method, mul(4.5, 2, 5), which has three parameters of double data type. 

 

Example of Method Overriding

  • C#

C#

using System;  
namespace Application 

   class Overriding 
   { 
       public virtual int mul(int x, int y) 
       { 
           return (x * y); 
       } 
   } 
   class Childbase: Overriding 
   { 
       public override int mul(int x, int y) 
       { 
           if (x <= 0 || y <= 0) 
           { 
              
              
               x = Convert.ToInt32(Console.ReadLine()); 
               
               y = Convert.ToInt32(Console.ReadLine()); 
           } 
           return (x * y); 
       } 
   } 
   class Example 
   { 
       static void Main(string[] args) 
       { 
           Overriding obj = new Overriding(); 
           Console.WriteLine("First Method :" + obj.mul(8, 8)); 
           obj = new Childbase(); 
           Console.WriteLine("Second Method :" + obj.mul(-6, 3)); 
           Console.WriteLine("Second Method :" + obj.mul(7, 3)); 
           Console.ReadLine(); 
       } 
   } 

 

Output

First Method :64

Second Method :0

Second Method :21

 

Explanation:

In the above example, two methods with the same name are created in the “Overriding” and “Childbase” class. In the “Overriding” class, the method multiplies the two numbers with less than zero value. But the “Childbase” class method checks for the negative value.

26. What are the differences between ref and out keywords?

ref keyword out keyword
If we use ref, the variable must be initialized before it is passed to a method. Variable does not need to be initialized before it is passed to a method.
ref assumes that variable has a vlaue. out assumes that there is no value of the variable and it will initialized by the method.
The variable passed to the method can be both read and written by the method. The variable passed can only be written by the method.

27. What are extension methods in C#?

Extension methods are a feature in C# that allow you to add methods to an existing class without modifying the class itself. Extension methods are defined as static methods in a static class, and they must be in the same namespace as the class being extended.

To use an extension method, you simply need to call it as if it were an instance method of the extended class. The first parameter of the extension method specifies the class being extended, and it is preceded by the this keyword. This tells the compiler that the method is an extension method and should be called as if it were a member of the extended class.

28. Does C# support multiple inheritances?

C# does not support multiple inheritances traditionally, where a class can inherit from multiple base classes. This is because multiple inheritance can lead to problems with ambiguity and complexity in the class hierarchy.

Instead, C# uses interfaces to provide similar functionality to multiple inheritance, which is an interface. An interface defines a contract that a class must implement but does not provide any implementation details.

29. What are the different types of comments in C#?

Various types of comments in C# are as follows:

  • XML comments 
    Example: ///This is an XML comment
     
  • Single Line comments
    Example: //This is a single-line comment
     
  • Multi-line comments
    Example: /* This is a multi-line comment */

 

30. List the steps of compiling a C# code.

Steps involved while compiling a C# code include the following:

  • Compilation of Source Code
     
  • Clubbing of Assembly code with the newly created code
     
  • Loading of CLR(Common Language Runtime).
     
  • Execution of assembly code through CLR.

Advanced Level C# Interview Questions

Below are some hard-level interview questions and answers. 

31. What are generics in C#.NET?

Ans: Generics in C#.NET is a feature that allows the creation of reusable code by creating classes, methods, and data structures that work with various data types without the need for duplicating code. Generics can parameterize a type or method by one or more data types, making the code more flexible and efficient. 

Generics provide type safety and enable better performance by avoiding the need for boxing and unboxing of value types. Generics are commonly used in collections, such as lists and dictionaries, as well as in algorithms and other areas of C# programming.

32. Mention different ways in which a method can be overloaded.

Ans: Different ways by which a method can be overloaded are:

  • Change the order of parameters in a method.
     
  • Change the number of parameters in a method.
     
  • Use different data types for parameters.
     

Example

  • C#

C#

using System;
namespace Overloading {
   public class Addition {
       public double sum(double a, double b) {
           double sum = a + b;
           return sum;
       }

       public double sum(double a, double b, double c) {
           double sum = a + b + c;
           return sum;
       }
   }

   class Example {
       public static void Main(string[] args) {
           Addition obj = new Addition();
           double a = 3.3;
           double b = 4.9;
           double s = 1.2;
           double sum = obj.sum(a, b, s);
           Console.WriteLine("Total sum: " + sum);

           double c = 3.3;
           double d = 6.3;
           double add = obj.sum(c, d);
           Console.WriteLine("Sum: " + add);
       }
   }
}

 

Output

Total sum: 9.4

Sum: 9.6

 

Explanation:

In the above example, the method sum is defined two times. First it contains two arguments to find the sum of two numbers, and second, it is defined with three arguments to find the sum of the three numbers.

33. Differentiate between early and late binding in C#.

Ans: Both early and late binding are examples of polymorphism concepts. Polymorphism enables a language to use the same name in many ways. For instance, the Add method can combine integers, doubles, and decimals.

The two types of polymorphism are:

Compile time polymorphism - Overloading or Early Binding.

Runtime polymorphism - Overriding or Late Binding.

Early Binding

In this, there are multiple methods with the same name but different parameter types(data types).

Example

using System;

namespace Overloading {
    public class Addition {
        public double sum(double a, double b) {
            return a + b;
        }

        public string sum(string a, string b) {
            return a + " " + c;
        }
    }

 

Late Binding

In this, there will be the same method name with the same number of parameters but not in the same class. Therefore we bind at the runtime in the child class. That’s the reason it is called late binding.

Example

using System;

namespace Overriding {
   class Addition {
      

      public sum( int a, int b) {
       return a + b;
      }

   }

   class ChildClass: Addition {
     
      public sum( int a, int b) {
       return a + b;
      }
   }

 

34. What are partial classes, and what is their use in C#?

Ans: Partial classes are a special feature in C# that implements the functionality of a single class into multiple physical files. When the application is compiled, all these multiple files are combined into a single class file. The partial keyword is used to split the class definition. 

Syntax

public partial Class_Name  
{
       // code
}

 

Partial classes in C# provide several advantages, including:

  • Organizing code.
  • Code reuse.
  • Separation of concerns.
  • Generated code.

Example

There are two files “Ninjas1” and “Ninjas2” that contain the “Ninjas” class.

Ninjas1.cs

public partial class Ninjas {
    private string name;
    private int age;
 
    public Geeks(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
}

 

Ninjas2.cs

public partial class Ninjas {
    public void print()
    {
        Console.WriteLine("Name is : " + name);
        Console.WriteLine("Age is : " + age);
    }
}

 

Below is the main class “Ninjas”, here the main method is not included.

public partial class Ninjas {
    private string name;
    private int age;
 
    public Geeks(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public void print()
    {
        Console.WriteLine("Name is : " + name);
        Console.WriteLine("Age is : " + age);
    }
}

35. How would you force Garbage Collection?

Ans: In C# Garbage Collection is a process that is managed by the .NET runtime, which automatically frees up memory that is no longer being used by the application. However, in certain cases, manually forcing Garbage Collection may be necessary.

In C#, you can use the GC.Collect() method to manually force Garbage Collection. The GC.Collect() method triggers the Garbage Collection process immediately rather than waiting for the .NET runtime to perform it automatically.

36. How would you create a responsive UI without impacting users in C#?

Ans: To create a responsive UI without impacting users in C#, there are a few techniques that can be used:

  1. Use asynchronous programming: Asynchronous programming enables the UI to remain responsive while background tasks are running. For example, you can use the async and await keywords to run long-running tasks in the background without blocking the UI thread.
     
  2. Use multithreading: By creating and managing multiple threads, you can offload heavy processing from the UI thread and keep the UI responsive. However, it's important to synchronize access to shared data across threads to avoid race conditions and other threading issues. 
     
  3. Use background workers: The BackgroundWorker class in C# provides a simple way to run long-running tasks in the background while keeping the UI responsive. It uses a separate thread to execute the task and provides events to report progress and completion.

37. What is the difference between a string and a StringBuilder in C#?

Ans: A string is an immutable data type, meaning you cannot change its value once you create a string. On the other hand, a StringBuilder is a mutable data type, allowing you to change its value and append new characters to it. 

StringBuilder is more efficient for concatenating strings or making multiple modifications to a string, as it does not create a new string instance for each change.

So if you want a string object not to change anywhere in the code then use string class otherwise StringBuilder.

 

Example of string object

  • C#

C#

using System;
namespace Application{
  class Example {
     public static void Main(String[] args){
         string s = "Coding ";
         s += "Ninjas";
         Console.WriteLine(s);
        
     }

   }
  }

 

Output

Coding Ninjas

 

Example of StringBuilder

  • C#

C#

using System;
using System.Text;


  class Example {
     public static void Main(){
         StringBuilder s = new StringBuilder("");
         s.Append("Coding ");
         s.Append("Ninjas");
         Console.WriteLine(s);
        
     }
  }

 

Output

Coding Ninjas

 

38. Why is the singleton pattern referred to as an anti-pattern in C#?

Ans: The Singleton pattern is often referred to as an anti-pattern in C# because it can introduce several issues and limitations that make code difficult to maintain and test. Some of the reasons why the Singleton pattern is considered an anti-pattern are:

  1. Global state: The Singleton pattern creates a global instance that is shared across the application. This can make it difficult to maintain and test since changes to the Singleton can affect the behavior of other parts of the application.
     
  2. Tight coupling: The Singleton pattern can create tight coupling between different parts of the application since the Singleton instance is often accessed directly from other classes. 
     
  3. Inflexibility: The Singleton pattern can be inflexible since it provides a single instance of an object that cannot be easily substituted or extended. This can make it difficult to adapt to changing requirements or to implement different behaviors for testing or other purposes.
     
  4. Testing challenges: The Singleton pattern can be difficult to test since it introduces a global state that can affect the behavior of other tests. It can also be difficult to substitute or mock the Singleton instance for testing purposes.

 

39. What is a virtual method in C#?

One of the features of object-oriented programming is Polymorphism. It allows you to use the same function to perform different actions according to your needs. 

In C#, you can use the virtual keyword to declare a method as a virtual method in a class. 

Now, if you inherit from this base class having a virtual method, then in the child class, you can override the virtual method using the override keyword, i.e., you can add the other implementation of the same method in the child class different from the parent class.

Example of virtual method in the base class:

public class Base
{
	public virtual void virtualMethod() {
		//Method implementation
	}
}

public class Derived : Base
{
	public override void virtualMethod() {
		//New implementation of virtualMethod
	}
}

40. List the features of read-only variables in C#.

The features of read-only variables in C# are as follows:

  • They are initialized at runtime.
     
  • They can be declared only at the class level.
     
  • They can be used with static modifiers.
     
  • The value of a readonly variable cannot be changed or reassigned.

41. What are stream reader and stream writer classes in C#?

The stream reader and stream writer classes inherit from the abstract base class “stream.” 

The abstract class Stream is used for writing and reading bytes from a text file.

Stream writer is used for writing to a file, while the stream reader is used for reading from a file. 

Some of the methods present in the:

  • Stream Reader Class: Close(), Peek(), and Read(). 
     
  • Stream Writer Class: Close(), Flush(), Write(bool value), WriteLine(), etc. 

42. What do you mean by boxing and unboxing in C#?

Boxing and unboxing are used for type conversion in C#. 

C# treats all the value types as objects. This feature of C# is emphasized by boxing and unboxing.

  • Boxing
    It converts the value type to an object or the interface’s data type implemented by the current value type.CLR performs the boxing of the value type and wraps the value in the System.object, and saves it in the heap area of the application domain. 
    It may use implicit code.
     
  • Unboxing
    Unboxing does the opposite of boxing, i.e., extracts the value type from the object or interface. It uses explicit code.

43. Differentiate between Task and Thread in C#.

The thread represents a separate program execution path, while a task represents an asynchronous operation. 

The task is used in the TPL(Task Parallel Library) and manages the parallel execution of code. It is easier to manage and use tasks in comparison to threads. 

Tasks provide a higher level of abstraction, while thread provides a lower level of abstraction.

Tasks help in the efficient utilization of resources than threads.

There can be multiple processes running simultaneously for a task. While a thread can have only one task at a time.

It is faster to create a task over a thread.

You can cancel a task in progress using cancellation tokens, but the thread does not support cancellation.

44. What is finally block in C#?

The finally block is used while handling exceptions in the code.

As we know, we use a try-and-catch block to handle exceptions. If an exception occurs while executing the try block, control reaches the catch block, and after that, control is transferred to the finally block. So, in the end, the finally block gets executed. 

Some of the most common uses of the finally block include releasing file handlers,  closing connections to the database, etc. 

Syntax of a general try-catch-block having a finally block is as follows:

try {
   // code block to be cheked for exception
} 
catch( ExceptionName e ) {
   // error handling code
} 
finally {
   // statements to be executed always
}

45. How do you implement exception handling in C#?

We use the following elements while implementing exception handling in C#:

  • try block
    It consists of code for which we need to check the exception.
     
  • catch block
    It is used for catching an exception and contains the code which will be executed once the exception occurs.
     
  • finally block
    It consists of code that is always executed irrespective of whether the exception occurs or not.
     
  • throw
    It is responsible for throwing an exception whenever it occurs instead of handling it.

46. What are dynamic type variables in C#?

As the name itself suggests, dynamic type variables can store data of any type. 

Type checking for such variables takes place at run time. 

You can define a dynamic type variable using a dynamic keyword in C#. 

Example:

dynamic newDynamicVariable = 2;

 

In most cases, the compiler compiles the dynamic variables to object types. But the final type is resolved only at runtime on the basis of their assigned value. 

If, after assigning one type of value, you reassign it to some other value of different type, then this type conversion takes place implicitly.

Example:

dynamic newDynamic1 = “hi”;
newDynamic1 = 10;
int s = newDynamic1;

47. Explain Anonymous types in C#.

You can create a new type without defining them beforehand using anonymous types in C#. 

It is a reference type, and you can define it using the var keyword. 

Anonymous types in C# can have multiple properties, all of which are read only. Basically, you can use it to bundle some read only properties in a single unit.

The difference between a C# class and anonymous types is that the classes can have fields and methods also, but anonymous types can only have properties.

You can access the anonymous type and its properties inside the method where it is defined. Therefore, its accessibility scope is limited.

Example:

var newAnonymousType {
property1 = “pr1”,
property2 = “pr2”
}

 

It is also possible to use nested anonymous types in C#. 

48. How is encapsulation implemented in C#?

Encapsulation is one of the most important and widely used feature of object oriented programming in C#. 

You can implements encapsulation in C# using various access modifiers like:

  • Public
    The public access modifier is used to expose a member of a class like class variables or functions to other classes or objects. This implies that you can access the public members of a class from outside the class.
     
  • Private
    The private access modifier conceals the class members like variables and functions from external world like other classes or objects. The private members of a class can only be accessed by the functions of same class.
     
  • Protected
    If you declare a class member as protected, then the children classes can access it. Thus, it is useful while implementing inheritance in object oriented programming as it allows to reuse the protected members like functions or variables.

49. Differentiate between constant and readonly in C#.

The values of the constant and readonly variables cannot be changed once assigned. 

But the only difference between them is that the const variables need to be initialized when defined, whereas the readonly variables can be defined at the runtime.

The following table summarizes the differences between the constant and readonly variables in C#. 

Constant

Readonly

You need to define it at compile time. It can be defined at compile time or runtime.
It is static, implicitly. It is instance-level or static.
It is copied across assemblies. It is shared across assemblies.
It does not allocate memory.  It allocates memory.

50. What is the use of the yield keyword in C#?

Following are the uses of the yield keyword in C#:

  • It is used for performing stateful iteration.
     
  • It helps to perform a custom iteration over a collection like lists, arrays, etc.


Using the yield keyword moves the control back and forth between the caller function and source and vice versa.

You can use the yield keyword in two forms:

  • yield return
    It is used for returning expressions at each iteration.
     
  • yield break
    It is used for terminating the iteration.

Frequently Asked Questions

What is C# and why C#?

C# is a modern general-purpose programming language developed by Microsoft. It is an object-oriented programming language. C# is a robust language mainly used to develop high-level software. C# strongly supports object-oriented paradigms with high versatility and community. It supports cross-platform development, which makes it highly usable.  

What is the main function of C#?

The main function of C# is to provide high support to object-oriented concepts and help in building robust, versatile, scalable, and cross-platform independent applications. 

Is C# and .NET same?

No, C# and .NET are not the same, although both are developed by Microsoft. C# is an object-oriented programming language, whereas .NET is a framework with support to multiple programming languages, and C# is one of the languages that can be used with the .NET framework to develop applications. 

Conclusion

In this article, we have discussed C# interview questions and their answers in three categories: easy, medium, and hard. You can also check out our other interview questions blogs:

Happy Learning!

Live masterclass