fbpx

Top 100 .net Developer Interview Questions and Answers

Top 100 .net Developer Interview Questions and Answers

Contents show

1. What is C# and its key features?

C# is an object-oriented programming language developed by Microsoft. It is part of the .NET platform and is commonly used for building Windows applications, web applications, and games. Key features include garbage collection, type safety, and platform independence through the Common Language Runtime (CLR).

Answer:

// Example of a basic C# program
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

Official Reference: C# Programming Guide


2. What is the difference between a class and an interface in C#?

A class is a blueprint for creating objects that defines the properties and behaviors they will have. An interface, on the other hand, is a contract that defines a set of methods a class must implement. While a class can provide implementation, an interface only declares the methods.

Answer:

// Example of a class and an interface in C#
class MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("This is a method in MyClass.");
    }
}

interface IMyInterface
{
    void MyMethod();
}

Official Reference: Classes and Structs | Interfaces


3. What is a delegate in C#?

A delegate in C# is a type that represents a method signature. It allows methods to be passed as parameters or returned as values, enabling dynamic invocation of methods at runtime.

Answer:

// Example of using a delegate in C#
delegate int MathOperation(int x, int y);

int Add(int a, int b)
{
    return a + b;
}

MathOperation operation = Add;
int result = operation(3, 4); // result will be 7

Official Reference: Delegates


4. What is the difference between StringBuilder and String in C#?

StringBuilder is a mutable type that allows efficient string concatenation by modifying the same instance. String, on the other hand, is immutable, meaning any modification creates a new string instance. For frequent string modifications, StringBuilder is more efficient.

Answer:

// Example of using StringBuilder in C#
StringBuilder sb = new StringBuilder();
sb.Append("Hello, ");
sb.Append("World!");
string result = sb.ToString(); // result will be "Hello, World!"

Official Reference: StringBuilder Class


5. What is LINQ and how is it used in C#?

LINQ (Language Integrated Query) is a set of features that extends C# to include query capabilities similar to SQL. It provides a standardized way to query various data sources such as arrays, collections, databases, XML, and more.

Answer:

// Example of using LINQ to query an array
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num; // LINQ query
foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output: 2, 4
}

Official Reference: LINQ (Language Integrated Query)


6. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await


7. Explain the difference between var and explicit data type declaration in C#.

var is used for implicit type declaration, allowing the compiler to infer the data type from the assignment. Explicit data type declaration specifies the type explicitly. Both approaches have the same effect at runtime.

Answer:

// Examples of var and explicit type declaration in C#
var number = 10; // Compiler infers int
int anotherNumber = 20; // Explicitly declared as int

Official Reference: var (C# Reference) | Type Inference (var)


8. What is an extension method in C#?

An extension method in C# allows developers to add new methods to existing types without modifying the original type or creating a new derived type. It is a way to extend the functionality of existing classes or interfaces.

Answer:

// Example of an extension method in C#
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}

Official Reference: Extension Methods (C# Programming Guide)


9. What is a lambda expression in C#?

A lambda expression in C# is a concise way to define anonymous methods or inline functions. It allows you to write code that can be treated as data, making it easy to pass as arguments or return from methods.

Answer:

// Example of a lambda expression in C#
Func<int, int, int> add = (x, y) => x + y;
int result = add(3, 4); // result will be 7

Official Reference: Lambda Expressions (C# Programming Guide)


10. What is Entity Framework and how is it used in C#?

Entity Framework (EF) is an object-relational mapping (ORM) framework that simplifies database interaction in C#. It enables developers to work with databases using .NET objects, eliminating the need for manual SQL queries.

Answer:

// Example of using Entity Framework to query a database
using (var context = new MyDbContext())
{
    var customers = context.Customers.Where(c => c.City == "Seattle").ToList();
}

Official Reference: Entity Framework Documentation


11. What is a nullable type in C#?

A nullable type in C# is a data type that can represent the normal range of values for its underlying value type, plus an additional null value. It’s useful when a value type needs to represent the absence of a value.

Answer:

// Example of using a nullable type in C#
int? nullableInt = null; // nullableInt can hold an integer or null

Official Reference: Nullable Types (C# Programming Guide)


12. What is ASP.NET and how does it relate to C#?

ASP.NET is a web application framework developed by Microsoft. It allows developers to build dynamic web applications using C# or other .NET languages. ASP.NET provides a platform for creating web pages, web services, and more.

Answer:

// Example of an ASP.NET MVC controller action method in C#
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Official Reference: ASP.NET Overview


13. What are the different types of collections in C#?

C# provides several types of collections such as lists, arrays, dictionaries, queues, stacks, and more. Each type serves a specific purpose and offers different methods for storing and manipulating data.

Answer:

// Example of using a List<T> in C#
List<string> names = new List<string>();
names.Add("John");
names.Add("Jane");

Official Reference: Collections (C# Programming Guide)


14. What is a constructor in C#?

A constructor in C# is a special method in a class that is automatically called when an instance of the class is created. It is used to initialize the object’s state and perform any necessary setup.

Answer:

// Example of a constructor in C#
public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

Official Reference: Constructors (C# Programming Guide)


15. What is an abstract class in C#?

An abstract class in C# is a class that cannot be instantiated directly and may contain abstract methods (methods without implementation). It serves as a blueprint for derived classes to implement.

Answer:

// Example of an abstract class in C#
public abstract class Shape
{
    public abstract double Area(); // Abstract method
}

Official Reference: Abstract Classes (C# Programming Guide)


16. What is the difference between IEnumerable and IQueryable in C#?

IEnumerable is used for querying in-memory collections like arrays and lists. IQueryable is used for querying external data sources like databases. IQueryable allows for deferred execution, optimizing queries.

Answer:

// Example of using IEnumerable and IQueryable in LINQ
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = numbers.Where(n => n > 3); // Executes in-memory

Official Reference: IEnumerable Interface | IQueryable Interface


17. What is a static class in C#?

A static class in C# is a class that cannot be instantiated, and its members are shared across all instances of the class. It is commonly used for utility classes and extension methods.

Answer:

// Example of a static class in C#
public static class MathOperations
{
    public static int Add(int x, int y)
    {
        return x + y;
    }
}

Official Reference: Static Classes and Static Class Members (C# Programming Guide)


18. What is a value type and a reference type in C#?

A value type holds the actual data, while a reference type holds a reference to the location where the data is stored. Value types are stored on the stack, while reference types are stored on the heap.

Answer:

// Examples of value type and reference type in C#
int value = 10; // value is a value type
string reference = "Hello"; // reference is a reference type

Official Reference: Value Types and Reference Types (C# Programming Guide)


19. What is a namespace in C#?

A namespace in C# is a way to organize and group related classes, interfaces, enums, and other types. It helps avoid naming conflicts between different parts of a program.

Answer:

// Example of using a namespace in C#
namespace MyNamespace
{
    class MyClass
    {
        // ...
    }
}

Official Reference: Namespaces (C# Programming Guide)


20. What is exception handling in C#?

Exception handling in C# is the process of dealing with runtime errors. It allows developers to gracefully handle errors and prevent the program from crashing.

Answer:

// Example of exception handling in C#
try
{
    int result = 10 / 0; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

Official Reference: Exception Handling (C# Programming Guide)


21. What is a generic class in C#?

A generic class in C# is a class that can work with any data type. It allows you to define classes and methods with placeholders for data types, making them more versatile and reusable.

Answer:

// Example of a generic class in C#
public class GenericList<T>
{
    private List<T> list = new List<T>();

    public void Add(T item)
    {
        list.Add(item);
    }
}

Official Reference: Generics (C# Programming Guide)


22. What is a property in C#?

A property in C# is a member of a class that provides a way to read or write the value of a private field. It allows controlled access to class fields while maintaining encapsulation.

Answer:

// Example of a property in C#
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Official Reference: Properties (C# Programming Guide)


23. What is an interface in C#?

An interface in C# defines a contract of methods and properties that a class must implement. It allows for multiple inheritance of behavior and is used to achieve abstraction and polymorphism.

Answer:

// Example of an interface in C#
public interface IShape
{
    double Area();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

Official Reference: Interfaces (C# Programming Guide)


24. What is a delegate in C#?

A delegate in C# is a type that represents a method signature. It allows methods to be passed as parameters or returned as values, enabling dynamic invocation of methods at runtime.

Answer:

// Example of using a delegate in C#
delegate int MathOperation(int x, int y);

int Add(int a, int b)
{
    return a + b;
}

MathOperation operation = Add;
int result = operation(3, 4); // result will be 7

Official Reference: Delegates (C# Programming Guide)


25. What is an anonymous type in C#?

An anonymous type in C# is a type created without explicitly defining it. It is useful for storing a set of read-only properties and is often used in LINQ queries.

Answer:

// Example of using an anonymous type in C#
var person = new { Name = "John", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Output: Name: John, Age: 30

Official Reference: Anonymous Types (C# Programming Guide)


26. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await (C# Programming Guide)


27. What is LINQ and how is it used in C#?

LINQ (Language Integrated Query) is a set of features that extends C# to include query capabilities similar to SQL. It provides a standardized way to query various data sources such as arrays, collections, databases, XML, and more.

Answer:

// Example of using LINQ to query an array in C#
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num; // LINQ query
foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output: 2, 4
}

Official Reference: LINQ (C# Programming Guide)


28. What is the difference between var and explicit data type declaration in C#?

var is used for implicit type declaration, allowing the compiler to infer the data type from the assignment. Explicit data type declaration specifies the type explicitly. Both approaches have the same effect at runtime.

Answer:

// Examples of var and explicit type declaration in C#
var number = 10; // Compiler infers int
int anotherNumber = 20; // Explicitly declared as int

Official Reference: var (C# Reference) | Type Inference (var)


29. What is an extension method in C#?

An extension method in C# allows developers to add new methods to existing types without modifying the original type or creating a new derived type. It is a way to extend the functionality of existing classes or interfaces.

Answer:

// Example of an extension method in C#
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}

Official Reference: Extension Methods (C# Programming Guide)


30. What is an attribute in C#?

An attribute in C# is a declarative tag that is used to convey

information about the behavior of elements in a program. It can be attached to classes, methods, properties, and other program elements.

Answer:

// Example of using an attribute in C#
[Serializable]
public class Person
{
    // ...
}

Official Reference: Attributes (C# Programming Guide)


21. What is a generic class in C#?

A generic class in C# is a class that can work with any data type. It allows you to define classes and methods with placeholders for data types, making them more versatile and reusable.

Answer:

// Example of a generic class in C#
public class GenericList<T>
{
    private List<T> list = new List<T>();

    public void Add(T item)
    {
        list.Add(item);
    }
}

Official Reference: Generics (C# Programming Guide)


22. What is a property in C#?

A property in C# is a member of a class that provides a way to read or write the value of a private field. It allows controlled access to class fields while maintaining encapsulation.

Answer:

// Example of a property in C#
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Official Reference: Properties (C# Programming Guide)


23. What is an interface in C#?

An interface in C# defines a contract of methods and properties that a class must implement. It allows for multiple inheritance of behavior and is used to achieve abstraction and polymorphism.

Answer:

// Example of an interface in C#
public interface IShape
{
    double Area();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

Official Reference: Interfaces (C# Programming Guide)


24. What is a delegate in C#?

A delegate in C# is a type that represents a method signature. It allows methods to be passed as parameters or returned as values, enabling dynamic invocation of methods at runtime.

Answer:

// Example of using a delegate in C#
delegate int MathOperation(int x, int y);

int Add(int a, int b)
{
    return a + b;
}

MathOperation operation = Add;
int result = operation(3, 4); // result will be 7

Official Reference: Delegates (C# Programming Guide)


25. What is an anonymous type in C#?

An anonymous type in C# is a type created without explicitly defining it. It is useful for storing a set of read-only properties and is often used in LINQ queries.

Answer:

// Example of using an anonymous type in C#
var person = new { Name = "John", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Output: Name: John, Age: 30

Official Reference: Anonymous Types (C# Programming Guide)


26. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await (C# Programming Guide)


27. What is LINQ and how is it used in C#?

LINQ (Language Integrated Query) is a set of features that extends C# to include query capabilities similar to SQL. It provides a standardized way to query various data sources such as arrays, collections, databases, XML, and more.

Answer:

// Example of using LINQ to query an array in C#
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num; // LINQ query
foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output: 2, 4
}

Official Reference: LINQ (C# Programming Guide)


28. What is the difference between var and explicit data type declaration in C#?

var is used for implicit type declaration, allowing the compiler to infer the data type from the assignment. Explicit data type declaration specifies the type explicitly. Both approaches have the same effect at runtime.

Answer:

// Examples of var and explicit type declaration in C#
var number = 10; // Compiler infers int
int anotherNumber = 20; // Explicitly declared as int

Official Reference: var (C# Reference) | Type Inference (var)


29. What is an extension method in C#?

An extension method in C# allows developers to add new methods to existing types without modifying the original type or creating a new derived type. It is a way to extend the functionality of existing classes or interfaces.

Answer:

// Example of an extension method in C#
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}

Official Reference: Extension Methods (C# Programming Guide)


30. What is an attribute in C#?

An attribute in C# is a declarative tag that is used to convey information about the behavior of elements in a program. It can be attached to classes, methods, properties, and other program elements.

Answer:

// Example of using an attribute in C#
[Serializable]
public class Person
{
    // ...
}

Official Reference: Attributes (C# Programming Guide)


31. What is a constructor in C#?

A constructor in C# is a special method in a class that is automatically called when an instance of the class is created. It is used to initialize the object’s state and perform any necessary setup.

Answer:

// Example of a constructor in C#
public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

Official Reference: Constructors (C# Programming Guide)


32. What is an abstract class in C#?

An abstract class in C# is a class that cannot be instantiated directly and may contain abstract methods (methods without implementation). It serves as a blueprint for derived classes to implement.

Answer:

// Example of an abstract class in C#
public abstract class Shape
{
    public abstract double Area(); // Abstract method
}

Official Reference: Abstract Classes (C# Programming Guide)


33. What is the difference between IEnumerable and IQueryable in C#?

IEnumerable is used for querying in-memory collections like arrays and lists. IQueryable is used for querying external data sources like databases. IQueryable allows for deferred execution, optimizing queries.

Answer:

// Example of using IEnumerable and IQueryable in LINQ
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = numbers.Where(n => n > 3); // Executes in-memory

Official Reference: IEnumerable Interface | IQueryable Interface


34. What is a static class in C#?

A static class in C# is a class that cannot be instantiated, and its members are shared across all instances of the class. It is commonly used for utility classes and extension methods.

Answer:

// Example of a static class in C#
public static class MathOperations
{
    public static int Add(int x, int y)
    {
        return x + y;
    }
}

Official Reference: Static Classes and Static Class Members (C# Programming Guide)


35. What is a value type and a reference type in C#?

A value type holds the actual data, while a reference type holds a reference to the location where the data is stored. Value types are stored on the stack, while reference types are stored on the heap.

Answer:

// Examples of value type and reference type in C#
int value = 10; // value is a value type
string reference = "Hello"; // reference is a reference type

Official Reference: Value Types and Reference Types (C# Programming Guide)


36. What is a namespace in C#?

A namespace in C# is a way to organize and group related classes, interfaces, enums, and other types. It helps avoid naming conflicts between different parts of a program.

Answer:

// Example of using a namespace in C#
namespace MyNamespace
{
    class MyClass
    {
        // ...
    }
}

Official Reference: Namespaces (C# Programming Guide)


37. What is exception handling in C#?

Exception handling in C# is the process of dealing with runtime errors. It allows developers to gracefully handle errors and prevent the program from crashing.

Answer:

// Example of exception handling in C#
try
{
    int result = 10 / 0; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

Official Reference: Exception Handling (C# Programming Guide)


38. What is LINQ and how is it used in C#?

LINQ (Language Integrated Query) is a set of features that extends C# to include query capabilities similar to SQL. It provides a standardized way to query various data sources such as arrays, collections, databases, XML, and more.

Answer:

// Example of using LINQ to query an array in C#
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num; // LINQ query
foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output: 2, 4
}

Official Reference: LINQ (C# Programming Guide)


39. What is the difference between var and explicit data type declaration in C#?

var is used for implicit type declaration, allowing the compiler to infer the data type from the assignment. Explicit data type declaration specifies the type explicitly. Both approaches have the same effect at runtime.

Answer:

// Examples of var and explicit type declaration in C#
var number = 10; // Compiler infers int
int anotherNumber = 20; // Explicitly declared as int

Official Reference: var (C# Reference) | Type Inference (var)


40. What is an extension method in C#?

An extension method in C# allows developers to add new methods to existing types without modifying the original type or creating a new derived type. It is a way to extend the functionality of existing classes or interfaces.

Answer:

// Example of an extension method in C#
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}

Official Reference: Extension Methods (C# Programming Guide)


41. What is an attribute in C#?

An attribute in C# is a declarative tag that is used to convey information about the behavior of elements in a program. It can be attached to classes, methods, properties, and other program elements.

Answer:

// Example of using an attribute in C#
[Serializable]
public class Person
{
    // ...
}

Official Reference: Attributes (C# Programming Guide)


Certainly, let’s continue:


42. What is the difference between == and Equals in C#?

== is used for comparing the values of two objects, while Equals is a method that is used to compare the contents or values of two objects. Equals can be overridden by classes for custom comparison logic.

Answer:

// Example of using == and Equals in C#
string str1 = "hello";
string str2 = "hello";
bool isEqual = (str1 == str2); // true
bool isEquals = str1.Equals(str2); // true

Official Reference: How to: Determine Whether Two Strings Are Equal (C# Programming Guide)


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

The using statement in C# is used to ensure that a resource is properly cleaned up or disposed of when it is no longer needed. It is commonly used with objects that implement IDisposable.

Answer:

// Example of using the using statement in C#
using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
    // Use the file stream
} // fs.Dispose() is automatically called

Official Reference: using Statement (C# Reference)


44. What is a lambda expression in C#?

A lambda expression in C# is a concise way to define anonymous methods, often used for one-off operations or when a delegate or expression tree is expected. It allows for the creation of delegate instances.

Answer:

// Example of using a lambda expression in C#
Func<int, int> square = x => x * x; // Defines a lambda expression
int result = square(5); // result will be 25

Official Reference: Lambda Expressions (C# Programming Guide)


45. What is garbage collection in C#?

Garbage collection in C# is the automatic process of reclaiming memory that is no longer in use by the program. It helps manage memory resources and frees developers from manual memory management.

Answer:

// Example of garbage collection in C#
// No explicit cleanup needed for objects

Official Reference: Garbage Collection (C# Programming Guide)


46. What is a using directive in C#?

A using directive in C# is used to include a namespace in a program. It allows you to reference types in a namespace without having to specify the full namespace path.

Answer:

// Example of using a using directive in C#
using System;

namespace MyNamespace
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Official Reference: Using Directive (C# Reference)


47. What is the purpose of the params keyword in C#?

The params keyword in C# allows a method to accept a variable number of arguments. It is useful when the number of arguments is not known at compile time.

Answer:

// Example of using the params keyword in C#
public int Sum(params int[] numbers)
{
    int result = 0;
    foreach (int num in numbers)
    {
        result += num;
    }
    return result;
}

Official Reference: params (C# Reference)


48. What is a thread in C#?

A thread in C# is a path of execution in a program. It allows for concurrent execution of code and is used for multitasking and parallel processing.

Answer:

// Example of creating and starting a thread in C#
using System.Threading;

public class Program
{
    public static void Main()
    {
        Thread thread = new Thread(new ThreadStart(DoWork));
        thread.Start();
    }

    static void DoWork()
    {
        // ...
    }
}

Official Reference: Thread Class (System.Threading)


49. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await (C# Programming Guide)


50. What is serialization in C#?

Serialization in C# is the process of converting an object or data structure into a format that can be easily stored, transmitted, or reconstructed later. It is commonly used for data storage and inter-process communication.

Answer:

// Example of serializing and deserializing an object in C#
[Serializable]
public class Person
{
    public string Name { get; set; }
}

// Serialization
Person person = new Person { Name = "John" };
FileStream fs = new FileStream("person.bin", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, person);
fs.Close();

// Deserialization
FileStream fs2 = new FileStream("person.bin", FileMode.Open);
Person deserializedPerson = (Person)formatter.Deserialize(fs2);
fs2.Close();

Official Reference: Serialization (C# Programming Guide)


51. What is a delegate in C#?

A delegate in C# is a type that represents a method signature. It allows methods to be passed as parameters, stored in variables, and invoked dynamically. Delegates are commonly used for implementing events and callbacks.

Answer:

// Example of using a delegate in C#
public delegate int MathOperation(int x, int y);

public class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

MathOperation operation = new Calculator().Add;
int result = operation(3, 4); // result will be 7

Official Reference: Delegates (C# Programming Guide)


52. What is an event in C#?

An event in C# is a mechanism for communication between objects. It allows a class to notify other classes or objects when an action or state change occurs.

Answer:

// Example of declaring and raising an event in C#
public class Button
{
    public event EventHandler Click;

    public void OnClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}

public class Program
{
    public static void Main()
    {
        Button button = new Button();
        button.Click += (sender, e) => Console.WriteLine("Button clicked!");
        button.OnClick(); // Output: Button clicked!
    }
}

Official Reference: Events (C# Programming Guide)


53. What is a collection in C#?

A collection in C# is a group of objects or elements that can be accessed and manipulated together. It provides a way to store, retrieve, and perform operations on a set of related items.

Answer:

// Example of using a collection in C#
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("David"); // Add an element
string firstElement = names[0]; // Access element by index
names.Remove("Bob"); // Remove an element

Official Reference: Collections (C# Programming Guide)


54. What is a generic type in C#?

A generic type in C# is a type that can work with any data type. It allows you to create classes, interfaces, and methods that are not specific to a particular data type.

Answer:

// Example of using a generic type in C#
public class Box<T>
{
    public T Content { get; set; }
}

Box<int> intBox = new Box<int>();
intBox.Content = 42;

Official Reference: Generics (C# Programming Guide)


55. What is a nullable type in C#?

A nullable type in C# is a type that can represent the absence of a value. It allows variables to be assigned a value or null.

Answer:

// Example of using a nullable type in C#
int? nullableInt = null;
if (nullableInt.HasValue)
{
    int value = nullableInt.Value;
}
else
{
    Console.WriteLine("The variable is null");
}

Official Reference: Nullable Types (C# Programming Guide)


56. What is an interface in C#?

An interface in C# is a contract that defines a set of methods, properties, and events that a class must implement. It allows for multiple inheritance of behavior.

Answer:

// Example of using an interface in C#
public interface IShape
{
    double Area();
    double Perimeter();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }

    public double Perimeter()
    {
        return 2 * Math.PI * Radius;
    }
}

Official Reference: Interfaces (C# Programming Guide)


57. What is a static constructor in C#?

A static constructor in C# is a special constructor that is used to initialize static members of a class. It is called once, the first time a class is accessed.

Answer:

// Example of using a static constructor in C#
public class Example
{
    public static int X { get; set; }
    static Example()
    {
        X = 42;
    }
}

Official Reference: Static Constructors (C# Programming Guide)


58. What is a value tuple in C#?

A value tuple in C# is a data structure that allows you to group together a fixed set of elements of different types. It provides a way to return multiple values from a method.

Answer:

// Example of using a value tuple in C#
public (string, int) GetPersonInfo()
{
    return ("John Doe", 30);
}

(string name, int age) person = GetPersonInfo();
Console.WriteLine($"Name: {person.name}, Age: {person.age}"); // Output: Name: John Doe, Age: 30

Official Reference: Value Tuples (C# Programming Guide)


59. What is a switch statement in C#?

A switch statement in C# is used to select one of many code blocks to be executed. It evaluates a variable or expression and matches it with one of the provided cases.

Answer:

// Example of using a switch statement in C#
int day = 3;
string dayName;
switch (day)
{
    case 1:
        dayName = "Sunday";
        break;
    case 2:
        dayName = "Monday";
        break;
    // ...
    default:
        dayName = "Invalid Day";
        break;
}

Official Reference: switch Statement (C# Reference)


60. What is an index in C#?

An index in C# is a way to access elements in a collection or array. It allows you to retrieve or modify the value of an element by specifying its position.

Answer:

// Example of using an index in C#
int[] numbers = { 1, 2, 3, 4, 5 };
int thirdNumber = numbers[2]; // thirdNumber will be 3

Official Reference: Indexes (C# 8.0 Specification)


61. What is an abstract class in C#?

An abstract class in C# is a class that cannot be instantiated directly. It serves as a blueprint for other classes and may contain abstract methods that must be implemented by derived classes.

Answer:

// Example of using an abstract class in C#
public abstract class Shape
{
    public abstract double Area();
}

public class Circle : Shape
{
    public double Radius { get; set; }

    public override double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

Official Reference: Abstract Classes (C# Programming Guide)


62. What is an extension method in C#?

An extension method in C# allows you to add new methods to existing types without modifying them. It is a way to extend the functionality of types defined elsewhere.

Answer:

// Example of creating an extension method in C#
public static class StringExtensions
{
    public static string Reverse(this string str)
    {
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

string original = "hello";
string reversed = original.Reverse(); // reversed will be "olleh"

Official Reference: Extension Methods (C# Programming Guide)


63. What is a LINQ in C#?

LINQ (Language Integrated Query) in C# is a set of features that provides a uniform way to query and manipulate data from different data sources. It allows queries to be written directly in C# code.

Answer:

// Example of using LINQ in C#
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num;

Official Reference: LINQ (C#)


64. What is a lambda expression in C#?

A lambda expression in C# is a concise way to define anonymous methods, often used for one-off operations or when a delegate or expression tree is expected. It allows for the creation of delegate instances.

Answer:

// Example of using a lambda expression in C#
Func<int, int> square = x => x * x; // Defines a lambda expression
int result = square(5); // result will be 25

Official Reference: Lambda Expressions (C# Programming Guide)


65. What is garbage collection in C#?

Garbage collection in C# is the automatic process of reclaiming memory that is no longer in use by the program. It helps manage memory resources and frees developers from manual memory management.

Answer:

// Example of garbage collection in C#
// No explicit cleanup needed for objects

Official Reference: Garbage Collection (C# Programming Guide)


66. What is a using directive in C#?

A using directive in C# is used to include a namespace in a program. It allows you to reference types in a namespace without having to specify the full namespace path.

Answer:

// Example of using a using directive in C#
using System;

namespace MyNamespace
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Official Reference: Using Directive (C# Reference)


67. What is the purpose of the params keyword in C#?

The params keyword in C# allows a method to accept a variable number of arguments. It is useful when the number of arguments is not known at compile time.

Answer:

// Example of using the params keyword in C#
public int Sum(params int[] numbers)
{
    int result = 0;
    foreach (int num in numbers)
    {
        result += num;
    }
    return result;
}

Official Reference: params (C# Reference)


68. What is a thread in C#?

A thread in C# is a path of execution in a program. It allows for concurrent execution of code and is used for multitasking and parallel processing.

Answer:

// Example of creating and starting a thread in C#
using System.Threading;

public class Program
{
    public static void Main()
    {
        Thread thread = new Thread(new ThreadStart(DoWork));
        thread.Start();
    }

    static void DoWork()
    {
        // ...
    }
}

Official Reference: Thread Class (System.Threading)


69. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await (C# Programming Guide)


70. What is serialization in C#?

Serialization in C# is the process of converting an object or data structure into a format that can be easily stored, transmitted, or reconstructed later. It is commonly used for data storage and inter-process communication.

Answer:

// Example of serializing and deserializing an object in C#
[Serializable]
public class Person
{
    public string Name { get; set; }
}

// Serialization
Person person = new Person { Name = "John" };
FileStream fs = new FileStream("person.bin", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, person);
fs.Close();

// Deserialization
FileStream fs2 = new FileStream("person.bin", FileMode.Open);
Person deserializedPerson = (Person)formatter.Deserialize(fs2);
fs2.Close();

Official Reference: Serialization (C# Programming Guide)


71. What is an attribute in C#?

An attribute in C# is a way to add metadata or declarative information to types, members, and other entities in a program. It provides additional information about the elements in your code.

Answer:

// Example of using an attribute in C#
[Serializable]
public class Person
{
    public string Name { get; set; }
}

Official Reference: Attributes (C# Programming Guide)


72. What is an anonymous type in C#?

An anonymous type in C# is a type without a name. It is used to encapsulate a set of read-only properties into a single object. Anonymous types are often used in LINQ queries.

Answer:

// Example of using an anonymous type in C#
var person = new { Name = "John Doe", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Output: Name: John Doe, Age: 30

Official Reference: Anonymous Types (C# Programming Guide)


73. What is a preprocessor directive in C#?

A preprocessor directive in C# is an instruction for the compiler that is processed before the code is compiled. It is used for conditional compilation, generating code, and other compile-time tasks.

Answer:

// Example of using a preprocessor directive in C#
#define DEBUG
using System;

public class Program
{
    public static void Main()
    {
#if (DEBUG)
        Console.WriteLine("Debug version");
#endif
    }
}

Official Reference: Preprocessor Directives (C# Programming Guide)


74. What is a design pattern in C#?

A design pattern in C# is a general reusable solution to a commonly occurring problem in software design. It provides a template for solving specific types of problems.

Answer:

// Example of using a design pattern in C#
// Singleton Pattern
public class Singleton
{
    private static Singleton instance;
    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

Official Reference: Design Patterns (C# Programming Guide)


75. What is inversion of control (IoC) in C#?

Inversion of Control (IoC) in C# is a design principle where the control flow of a program is inverted. It means that a framework or container controls the flow of execution, and the developer’s code plugs into this framework.

Answer:

// Example of using inversion of control in C#
// Using a DI Container like Autofac
var builder = new ContainerBuilder();
builder.RegisterType<Logger>().As<ILogger>();
builder.RegisterType<EmailSender>().As<IMessageSender>();
var container = builder.Build();

var logger = container.Resolve<ILogger>();
var sender = container.Resolve<IMessageSender>();

Official Reference: Inversion of Control Containers and the Dependency Injection pattern (C#)


76. What is a unit test in C#?

A unit test in C# is a method or function that checks if a specific part of your code works correctly. It verifies that individual units of code (methods or functions) behave as expected.

Answer:

// Example of writing a unit test in C# using NUnit
[TestFixture]
public class CalculatorTests
{
    [Test]
    public void Add_WhenCalled_ReturnsSum()
    {
        Calculator calculator = new Calculator();
        int result = calculator.Add(3, 4);
        Assert.AreEqual(7, result);
    }
}

Official Reference: Unit Testing in C# (NUnit)


77. What is a mocking framework in C#?

A mocking framework in C# is a tool that allows you to create mock or fake objects for testing purposes. It helps isolate the code you want to test from the dependencies.

Answer:

// Example of using a mocking framework (Moq) in C#
var mockLogger = new Mock<ILogger>();
mockLogger.Setup(logger => logger.Log(It.IsAny<string>())).Verifiable();
var myService = new MyService(mockLogger.Object);

Official Reference: Moq – The simplest mocking library for .NET


78. What is dependency injection (DI) in C#?

Dependency Injection (DI) in C# is a design pattern that involves injecting dependencies (e.g., objects, services) into a class rather than creating them inside the class. It promotes loose coupling and facilitates unit testing.

Answer:

// Example of using dependency injection in C#
public class OrderService
{
    private readonly IOrderRepository _orderRepository;

    public OrderService(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public void PlaceOrder(Order order)
    {
        _orderRepository.AddOrder(order);
    }
}

Official Reference: Dependency injection in .NET


79. What is asynchronous programming in C#?

Asynchronous programming in C# allows tasks to be performed concurrently, improving responsiveness in applications. It is achieved using async and await keywords, allowing non-blocking execution.

Answer:

// Example of asynchronous programming in C#
public async Task<string> DownloadContentAsync(string url)
{
    HttpClient client = new HttpClient();
    return await client.GetStringAsync(url);
}

Official Reference: Asynchronous programming with async and await (C#)


80. What is the difference between IEnumerable and IQueryable in C#?

IEnumerable in C# is an interface for collections that can be enumerated. IQueryable is an interface for querying data sources that implement IQueryable<T>. While both allow iteration, IQueryable supports querying databases.

Answer:

// Example of using IEnumerable and IQueryable in C#
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var queryableNumbers = numbers.AsQueryable();

Official Reference: IEnumerable Interface, IQueryable Interface


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

The using statement in C# is used to specify namespaces in which objects are defined. It ensures that the resources are properly disposed of after use.

Answer:

// Example of using the using statement in C#
using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
    // Perform operations with the file stream
}

Official Reference: using Statement (C# Reference)


82. What is the difference between readonly and const in C#?

In C#, readonly is used to create fields that can be assigned a value once (usually in the constructor). const creates fields with a constant value that cannot be changed.

Answer:

// Example of using readonly and const in C#
public class Constants
{
    public readonly int ReadOnlyValue;
    public const int ConstantValue = 5;

    public Constants(int value)
    {
        ReadOnlyValue = value; // Assignable in the constructor
    }
}

Official Reference: readonly (C# Reference) , const (C# Reference)


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

The lock statement in C# is used to ensure that a block of code is executed by only one thread at a time. It is used to prevent race conditions in multithreaded programs.

Answer:

// Example of using the lock statement in C#
public class Counter
{
    private int count = 0;
    private object lockObject = new object();

    public void Increment()
    {
        lock (lockObject)
        {
            count++;
        }
    }

    public int GetCount()
    {
        lock (lockObject)
        {
            return count;
        }
    }
}

Official Reference: lock Statement (C# Reference)


84. What is a delegate in C#?

A delegate in C# is a type that represents references to methods with a particular parameter list and return type. It allows methods to be passed as arguments, returned as values, and stored in data structures.

Answer:

// Example of using a delegate in C#
public delegate int MathOperation(int x, int y);

public class Calculator
{
    public int Add(int a, int b) { return a + b; }
    public int Subtract(int a, int b) { return a - b; }
}

// Using the delegate
MathOperation operation = new MathOperation(calculator.Add);
int result = operation(3, 4); // result will be 7

Official Reference: Delegates (C# Programming Guide)


85. What is a lambda expression in C#?

A lambda expression in C# is a concise way to define anonymous methods, often used for one-off operations or when a delegate or expression tree is expected. It allows for the creation of delegate instances.

Answer:

// Example of using a lambda expression in C#
Func<int, int> square = x => x * x; // Defines a lambda expression
int result = square(5); // result will be 25

Official Reference: Lambda Expressions (C# Programming Guide)


86. What is garbage collection in C#?

Garbage collection in C# is the automatic process of reclaiming memory that is no longer in use by the program. It helps manage memory resources and frees developers from manual memory management.

Answer:

// Example of garbage collection in C#
// No explicit cleanup needed for objects

Official Reference: Garbage Collection (C# Programming Guide)


87. What is a using directive in C#?

A using directive in C# is used to include a namespace in a program. It allows you to reference types in a namespace without having to specify the full namespace path.

Answer:

// Example of using a using directive in C#
using System;

namespace MyNamespace
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Official Reference: Using Directive (C# Reference)


88. What is the purpose of the params keyword in C#?

The params keyword in C# allows a method to accept a variable number of arguments. It is useful when the number of arguments is not known at compile time.

Answer:

// Example of using the params keyword in C#
public int Sum(params int[] numbers)
{
    int result = 0;
    foreach (int num in numbers)
    {
        result += num;
    }
    return result;
}

Official Reference: params (C# Reference)


89. What is a thread in C#?

A thread in C# is a path of execution in a program. It allows for concurrent execution of code and is used for multitasking and parallel processing.

Answer:

// Example of creating and starting a thread in C#
using System.Threading;

public class Program
{
    public static void Main()
    {
        Thread thread = new Thread(new ThreadStart(DoWork));
        thread.Start();
    }

    static void DoWork()
    {
        // ...
    }
}

Official Reference: Thread Class (System.Threading)


90. What is the async and await keywords in C#?

The async and await keywords in C# are used to perform asynchronous programming. async indicates that a method can perform an asynchronous operation, and await is used inside an async method to wait for the result of an asynchronous operation.

Answer:

// Example of using async and await in C#
async Task<string> DownloadAsync()
{
    HttpClient client = new HttpClient();
    string result = await client.GetStringAsync("http://www.example.com");
    return result;
}

Official Reference: Async and Await (C# Programming Guide)


91. What is an interface in C#?

An interface in C# is a reference type that defines a contract for the methods, properties, and events that a class must implement. It provides a blueprint for a class’s behavior.

Answer:

// Example of using an interface in C#
public interface IShape
{
    double Area(); // Method declaration
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

Official Reference: Interfaces (C# Programming Guide)


92. What is a base class in C#?

A base class in C# is a class from which other classes inherit. It serves as the foundation for derived classes and provides common functionality to them.

Answer:

// Example of using a base class in C#
public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

Official Reference: Inheritance in C# (C# Programming Guide)


93. What is a sealed class in C#?

A sealed class in C# is a class that cannot be inherited. It prevents other classes from deriving from it.

Answer:

// Example of using a sealed class in C#
sealed class FinalClass
{
    // Class implementation
}

Official Reference: sealed (C# Reference)


94. What is a static class in C#?

A static class in C# is a class that cannot be instantiated, and all its members are static. It is used to group related functionalities that do not depend on specific instance data.

Answer:

// Example of using a static class in C#
public static class MathOperations
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

Official Reference: static (C# Reference)


95. What is the purpose of the this keyword in C#?

The this keyword in C# refers to the current instance of a class. It is used to differentiate between class members and parameters with the same name.

Answer:

// Example of using the this keyword in C#
public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        this.Name = name; // Using this to refer to the instance variable
    }
}

Official Reference: this (C# Reference)


96. What is operator overloading in C#?

Operator overloading in C# allows you to define custom behavior for operators (+, -, *, /, etc.) when used with user-defined types.

Answer:

// Example of operator overloading in C#
public class Complex
{
    public int Real { get; set; }
    public int Imaginary { get; set; }

    public static Complex operator +(Complex a, Complex b)
    {
        return new Complex { Real = a.Real + b.Real, Imaginary = a.Imaginary + b.Imaginary };
    }
}

Official Reference: Operator Overloading (C# Programming Guide)


97. What is the as operator in C#?

The as operator in C# is used to perform explicit reference type conversions. If the conversion is not possible, it returns null instead of throwing an exception.

Answer:

// Example of using the as operator in C#
object obj = "Hello";
string str = obj as string;
if (str != null)
{
    Console.WriteLine(str);
}

Official Reference: as (C# Reference)


98. What is the purpose of the checked and unchecked keywords in C#?

The checked and unchecked keywords in C# are used to control the behavior of arithmetic overflow. checked ensures that overflow is checked, while unchecked suppresses the overflow check.

Answer:

// Example of using checked and unchecked in C#
int max = int.MaxValue;
checked
{
    int result = max + 1; // Throws OverflowException
}

unchecked
{
    int result = max + 1; // Result wraps around
}

Official Reference: checked (C# Reference), unchecked (C# Reference)


99. What is a finalizer in C#?

A finalizer in C# (also known as a destructor) is a special method that is automatically called when an object is about to be garbage collected. It is used to perform cleanup operations.

Answer:

// Example of using a finalizer in C#
public class MyClass
{
    ~MyClass()
    {
        // Cleanup code
    }
}

Official Reference: Destructors (C# Programming Guide)


100. What is a generic class in C#?

A generic class in C# is a class that is parameterized by one or more types. It allows you to define classes with placeholders for the types of their fields, methods, parameters, etc.

Answer:

// Example of using a generic class in C#
public class GenericList<T>
{
    private List<T> list = new List<T>();

    public void Add(T item)
    {
        list.Add(item);
    }

    public T Get(int index)
    {
        return list[index];
    }
}

Official Reference: Generics (C# Programming Guide)