Search Jobs

Ticker

6/recent/ticker-posts

C# Interview Questions

Top most asked C# interview questions along with brief answers and examples:


1. What is C#?

   - C# (pronounced C sharp) is a modern, object-oriented programming language developed by Microsoft as part of the .NET platform.


2. Explain the difference between ref and out parameters.

   - The ref keyword is used to pass a variable by reference, allowing the called method to modify the variable. The out keyword is similar, but the variable doesn't need to be initialized before passing.

Example: 

 

   void ModifyWithRef(ref int x) { /* Modify x */ }

   void InitializeAndModifyWithOut(out int y) { y = 10; /* Modify y */ }

  


3. What is the difference between IEnumerable and IQueryable ?

   - IEnumerable is used for querying in-memory collections, while IQueryable is used for querying databases.


4. Explain the concept of boxing and unboxing.

   - Boxing is converting a value type to a reference type, and unboxing is converting a reference type back to a value type.


 

   int num = 42;

   object obj = num;   // Boxing

   int backToNum = (int)obj;   // Unboxing

  


5. What is the var keyword used for?

   - var is used to implicitly declare a variable, letting the compiler determine the type.


 

   var name = "John";   // Compiler infers string type

  


6. What is the async and await keywords used for?

   - async is used to define asynchronous methods, and

await is used to asynchronously wait for a task to complete.


 

   async Task<int> GetDataAsync() { /* Asynchronous operation */ }

  


7. What is a delegate?

   - A delegate is a type that represents references to methods with a specific signature. It is similar to a function pointer in C++.


 

   delegate void MyDelegate(string message);

  


8. Explain the Singleton pattern.

   - The Singleton pattern ensures a class has only one instance and provides a global point of access to it.


 

   public sealed class Singleton

   {

    private static Singleton instance;

    private static readonly object lockObject = new object();


    private Singleton() { }


    public static Singleton Instance

    {

        get

        {

            lock (lockObject)

            {

                return instance ?? (instance = new Singleton());

            }

        }

    }

   }

  


9. What is LINQ?

   - LINQ (Language Integrated Query) is a set of features in C# that allows for querying collections of objects using a SQL-like syntax.


 

   var result = from person in people

             where person.Age > 18

             select person.Name;

  


10. Explain the concept of partial classes.

- Partial classes allow a class to be defined in multiple files. This is useful for separating generated code from user code.


  

// File1.cs

partial class MyClass

{

     // Part of the class

}


// File2.cs

partial class MyClass

{

     // Another part of the class

}


11. What is the difference between String and StringBuilder ?

- String is immutable, meaning once a string is created, it cannot be changed. StringBuilder is mutable and allows for efficient string manipulation.


  

// Using String

string greeting = "Hello ";

greeting += "World";


// Using StringBuilder

StringBuilder sb = new StringBuilder("Hello ");

sb.Append("World");


12. Explain the SOLID principles.

- SOLID is an acronym for five design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. They aim to make software designs more understandable, flexible, and maintainable.


13. What is the difference between IEnumerable<T> and IList<T> ?

-IEnumerable<T> is a read-only forward-only cursor of items, while IList<T> is a collection of items with index-based access and allows modifications.


  

IEnumerable<int> numbers = new List<int> { 1, 2, 3 };

IList<int> numberList = new List<int> { 1, 2, 3 };


// Example of modification using IList

numberList[0] = 10;


14. How does garbage collection work in C#?

- Garbage collection automatically manages the memory by reclaiming the memory occupied by objects that are no longer in use.


15. What is the difference between Dispose and Finalize ?

- Dispose is a method used for releasing unmanaged resources explicitly, while Finalize is a method that is automatically called by the garbage collector before an object is reclaimed.


16. What is the purpose of the using statement in C#?

- The using statement is used to ensure that IDisposable objects are properly disposed of, releasing resources when they are no longer needed.


  

using (StreamReader reader = new StreamReader("file.txt"))

{

     // Code that uses the StreamReader

} // The StreamReader is automatically disposed of here


17. Explain the difference between struct and class.

- struct is a value type stored on the stack, while

class is a reference type stored on the heap.


  

struct Point

{

     public int X;

     public int Y;

}


class PointClass

{

     public int X { get; set; }

     public int Y { get; set; }

}


18. What is a lambda expression, and how is it used?

- A lambda expression is an anonymous function that can have input parameters and a body. It is often used in LINQ queries and functional programming.


  

Func<int, int, int> add = (a, b) => a + b;

int result = add(3, 4); // Result is 7


19. What is the purpose of the volatile keyword?

- The volatile keyword ensures that a variable's value is always read from and written to the main memory, preventing optimizations by the compiler that might lead to unexpected behavior in multithreaded scenarios.


  

private volatile bool flag = true;


20. How does exception handling work in C#?

- Exception handling in C# is done using try

, catch , finally , and throw keywords. Exceptions are objects that represent errors during the execution of a program.


  

try

{

     // Code that might throw an exception

}

catch (Exception ex)

{

     // Handle the exception

}

finally

{

     // Code that runs regardless of whether an exception was thrown

}


21. What is the purpose of the async and await keywords in C#?

- async is used to define asynchronous methods, and

await is used to asynchronously wait for a task to complete, allowing the calling code to continue execution.


  

async Task<int> GetDataAsync()

{

     // Asynchronous operation

     return await SomeAsyncMethod();

}


22. Explain the concept of inheritance in C#.

- Inheritance allows a class to inherit properties and methods from another class. It promotes code reusability and supports the "is-a" relationship.


  

class Animal

{

     public void Eat() { /* Implementation */ }

}


class Dog : Animal

{

     public void Bark() { /* Implementation */ }

}


23. What is the difference between sealed and static classes?

- A sealed class cannot be inherited, while a

static class cannot be instantiated and is used for grouping related methods and properties.


  

sealed class SealedClass { /* Implementation */ }


static class StaticClass { /* Implementation */ }


24. How does the using statement differ from try...finally in managing resources?

- Th using statement is specifically designed for managing resources that implement IDisposable

and automatically disposes of the resource when the block is exited.


  

using (StreamReader reader = new StreamReader("file.txt"))

{

     // Code that uses the StreamReader

} // The StreamReader is automatically disposed of here


25. What are indexers in C#?

- Indexers allow instances of a class or struct to be indexed like arrays. They are defined using this keyword.


  

class SampleCollection

{

     private int[] array = new int[5];


     public int this[int index]

     {

         get { return array[index]; }

         set { array[index] = value; }

     }

}


26. Explain the concept of polymorphism in C#.

- Polymorphism allows objects of different types to be treated as objects of a common base type. It includes method overloading and method overriding.


  

class Animal

{

     public virtual void MakeSound() { /* Default implementation */ }

}


class Dog : Animal

{

     public override void MakeSound() { /* Dog-specific implementation */ }

}


27. What is the purpose of the yield keyword in C#?

- The yield keyword is used to create iterator methods, allowing the deferred execution of a collection.


  

public IEnumerable<int> GetNumbers()

{

     yield return 1;

     yield return 2;

     yield return 3;

}


28. Explain the Observer design pattern.

- The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


  

public class Subject

{

     private List<IObserver> observers = new List<IObserver>();


     public void Attach(IObserver observer) { /* Implementation */ }


     public void Notify() { /* Implementation */ }

}


29. What is the purpose of the params

keyword in C#?

- The params keyword allows a method to accept a variable number of parameters of a specified type.


  

public int Sum(params int[] numbers)

{

     return numbers.Sum();

}


30. How does dependency injection work in C#?

- Dependency Injection (DI) is a design pattern where the dependencies of a class are injected from the outside, promoting loose coupling.


  

public class UserService

{

     private readonly IRepository repository;


     public UserService(IRepository repository)

     {

         this.repository = repository;

     }

}


31. Explain the purpose of the try...catch...when statement.

   - The when clause in a catch block allows you to specify a condition that must be true for the catch block to be executed.


 

   try

   {

    // Code that might throw an exception

   }

   catch (Exception ex) when (ex.Message.Contains("specific error"))

   {

    // Handle the exception based on a condition

   }

  


32. What is the role of the Action and Func delegates in C#?

   -

Action is a delegate representing a method that takes no parameters and returns void.

Func is a generic delegate with parameters and a return type.


 

   Action<string> logMessage = (msg) => Console.WriteLine(msg);

   Func<int, int, int> add = (a, b) => a + b;

  


33. How does the as operator differ from casting in C#?

   - The as operator is used for safe type casting, returning null if the conversion is not possible, while casting can throw an InvalidCastException.


 

   object obj = "Hello";

   string str1 = obj as string; // Safe casting

   string str2 = (string)obj;   // Casting (may throw exception)

  


34. Explain the concept of anonymous types in C#.

   - Anonymous types allow you to create objects without explicitly defining a type. The compiler generates a type with read-only properties based on the initializer.


 

   var person = new { Name = "John", Age = 25 };

   Console.WriteLine($"{person.Name}, {person.Age}");

  


35. What is the purpose of the nameof operator in C#?

   - The nameof operator returns the name of a variable, type, or member as a string, providing a way to avoid hardcoding names.


 

   string propertyName = nameof(MyClass.MyProperty);

  


36. Explain the concept of extension methods in C#.

   - Extension methods allow you to add new methods to existing types without modifying them. They are defined in static classes and must be in the same namespace.


 

   public static class StringExtensions

   {

    public static bool IsNullOrEmpty(this string str)

    {

        return string.IsNullOrEmpty(str);

    }

   }

  


37. What is the purpose of the lock statement in C#?

   - The lock statement is used for mutual exclusion, preventing multiple threads from entering a critical section concurrently.


 

   private static object lockObject = new object();


   lock (lockObject)

   {

    // Critical section protected by the lock

   }

  


38. Explain the concept of covariance and contravariance in C#.

   - Covariance allows you to use a more derived type than originally specified, while contravariance allows you to use a less derived type.


 

   // Covariance

   IEnumerable<object> objects = new List<string>();


   // Contravariance

   Action<string> stringAction = (str) => Console.WriteLine(str);

   Action<object> objectAction = stringAction;

  


39. What is the purpose of the checked and unchecked

keywords in C#?

   - The checked and unchecked keywords are used to control overflow checking in arithmetic operations. By default, arithmetic operations are unchecked.


 

   int result1 = unchecked(int.MaxValue + 1);

   int result2 = checked(int.MaxValue + 1); // Throws OverflowException

  


40. How does the Enumerable.Range method work in C#?

   -Enumerable.Range generates a sequence of integers within a specified range.


 

   IEnumerable<int> numbers = Enumerable.Range(1, 5); // Generates 1, 2, 3, 4, 5

  


41. What is the purpose of the async/await pattern in C#?

   - The async/await pattern simplifies asynchronous programming, allowing the creation of asynchronous methods that can be awaited without blocking the calling thread.


 

   async Task<int> GetDataAsync()

   {

    // Asynchronous operation

    return await SomeAsyncMethod();

   }

  


42. Explain the concept of garbage collection in C# and how it helps manage memory.

   - Garbage collection is an automatic memory management feature in C# that identifies and reclaims memory occupied by objects that are no longer reachable.


43. What is a delegate multicast in C#?

   - Delegate multicast allows a delegate instance to invoke multiple methods. It is achieved using the += and -= operators.


 

   delegate void MyDelegate(string message);


   MyDelegate multiDelegate = Method1;

   multiDelegate += Method2; // Multicast

   multiDelegate -= Method1; // Remove from multicast

  


44. Explain the difference between readonly and const in C#?

   -

const is a compile-time constant, and its value cannot be changed. readonly allows a value to be assigned at runtime and remains constant throughout the object's lifetime.


 

   const int MaxValue = 100;

   readonly int RuntimeValue;


   public MyClass(int value)

   {

    RuntimeValue = value; // Set at runtime

   }

  


45. How does the Tuple class work in C#?

   - Tuple is a data structure in C# that holds an ordered collection of elements, each potentially of a different type.


 

   var myTuple = Tuple.Create(1, "Hello", true);

   Console.WriteLine(myTuple.Item1); // Access elements by Item1, Item2, etc.

  


46. Explain the purpose of the nameof operator in C# and provide an example.

   - The nameof operator returns the name of a variable, type, or member as a string, reducing hardcoding and improving maintainability.


 

   string propertyName = nameof(MyClass.MyProperty);

  


47. What is the purpose of the AutoResetEvent class in C#?

   - AutoResetEvent is a synchronization primitive that signals one waiting thread when an event occurs and automatically resets the event for subsequent threads.


 

   AutoResetEvent autoEvent = new AutoResetEvent(false);


   // Thread 1

   autoEvent.WaitOne(); // Waits for signal


   // Thread 2

   autoEvent.Set(); // Signals waiting thread

  


48. Explain the concept of boxing and unboxing in C#.

   - Boxing is the process of converting a value type to a reference type, and unboxing is the process of converting a reference type back to a value type.


 

   int num = 42;

   object obj = num;   // Boxing

   int backToNum = (int)obj;   // Unboxing

  


49. What is the purpose of the FileStream class in C#?

   - FileStream is used for reading from, writing to, and manipulating files. It provides low-level access to file I/O operations.


 

   using (FileStream fs = new FileStream("example.txt", FileMode.Open))

   {

    // Perform file operations

   }

  


50. Explain the use of the Thread.Sleep method in C#.

   -Thread.Sleep pauses the execution of the current thread for a specified duration, allowing other threads to execute during the sleep period.


 

   Console.WriteLine("Before Sleep");

   Thread.Sleep(1000); // Sleep for 1 second

   Console.WriteLine("After Sleep");

  






Post a Comment

0 Comments