C# interview questions with answers

Rumman Ansari   2023-05-30   Developer   tcs preparation > C# interview questions with answers   249 Share

C# interview questions with answers

  1. What is C#?

C# (pronounced "C sharp") is a programming language developed by Microsoft as part of the .NET framework. It is a modern, object-oriented language designed for building robust and scalable applications.

  1. What are the features of C#?

Some of the key features of C# include:

  • Object-oriented programming support
  • Garbage collection for automatic memory management
  • Strong typing with type safety
  • Language interoperability through the .NET framework
  • Exception handling for robust error management
  • Support for multithreading and asynchronous programming
  • Generics for code reuse and type safety
  • LINQ (Language-Integrated Query) for data querying and manipulation
  1. What is the difference between value types and reference types in C#?

In C#, value types store their actual values, while reference types store references to the memory location where the data is stored.

  • Value types: Value types include primitive types such as int, float, bool, and structs. They are stored on the stack and directly hold their values.
  • Reference types: Reference types include classes, arrays, and delegates. They are stored on the heap, and variables of reference types hold references (pointers) to the memory location where the actual data is stored.
  1. What is the difference between a class and a struct in C#?

In C#, both classes and structs are used to define custom types, but they have some differences:

  • Memory allocation: Classes are reference types and are allocated on the heap, while structs are value types and are allocated on the stack or inline within other structures.
  • Default behavior: Classes have a default constructor, while structs don't. Classes are nullable by default, while structs are not.
  • Performance: Structs are generally more efficient in terms of memory usage and performance compared to classes, especially for small, lightweight objects.
  1. What is the difference between method overloading and method overriding?
  • Method overloading: Method overloading is a feature that allows defining multiple methods with the same name but different parameters in the same class. The compiler determines which method to invoke based on the number, types, and order of the arguments passed.

  • Method overriding: Method overriding is a feature of inheritance that allows a derived class to provide its own implementation of a method that is already defined in the base class. The method in the derived class must have the same name, return type, and parameters as the base class method. Method overriding is achieved using the override keyword.

  1. What is the difference between an abstract class and an interface?
  • Abstract class: An abstract class is a class that cannot be instantiated and is typically used as a base class for other classes. It may contain abstract and non-abstract (concrete) methods, fields, and properties. Subclasses must provide implementations for the abstract methods. An abstract class can also have constructors and fields.

  • Interface: An interface defines a contract that a class must adhere to. It only contains method signatures, properties, and events but does not provide any implementation. A class can implement multiple interfaces, and it must provide implementations for all the members defined in those interfaces.

  1. What is the difference between StringBuilder and String in C#?
  • StringBuilder: StringBuilder is a mutable string type in C#. It provides methods to modify the contents of a string without creating a new object each time. It is more efficient when performing frequent modifications to a string, such as concatenations or appends, as it avoids unnecessary memory allocations.

  • String: String is an immutable type in C#. Once created, its value cannot be changed. Any modifications to a string result in creating a new string object. Immutable strings are useful for scenarios where the data needs to be constant and cannot be modified.

 

  1. What is the difference between IEnumerable and IQueryable?
  • IEnumerable: IEnumerable is an interface that represents a sequence of elements and provides the ability to iterate over them using foreach. It is suitable for querying in-memory collections like arrays or lists.

  • IQueryable: IQueryable is an interface that represents a queryable data source, such as a database or remote service. It extends IEnumerable and allows composing queries using LINQ. The queries defined using IQueryable are executed when enumerated.

  1. What is the difference between var and dynamic in C#?
  • var: var is used for implicitly typing local variables at compile time. The compiler determines the actual type of the variable based on the expression it is assigned to. However, once the type is inferred, it cannot be changed.

  • dynamic: dynamic is used to declare variables whose type will be determined at runtime. It allows for late binding and enables performing dynamic operations on the variable. The type checking is deferred until runtime, which can result in potential runtime errors if the operations are not valid.

  1. What are the different access modifiers in C#?

C# provides several access modifiers to control the accessibility of types and members:

  • public: The type or member is accessible from any other code.
  • private: The type or member is only accessible within the containing type.
  • protected: The type or member is accessible within the containing type and its derived types.
  • internal: The type or member is accessible within the same assembly (project).
  • protected internal: The type or member is accessible within the same assembly or from derived types in other assemblies.
  1. What are delegates in C#?

Delegates are a type-safe way of encapsulating a reference to a method. They allow methods to be assigned to variables, passed as parameters to other methods, and invoked indirectly through the delegate. Delegates are often used for implementing events, callbacks, and asynchronous programming patterns in C#.

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

The using statement in C# is used for automatic resource management. It ensures that the resources (such as file streams, database connections, etc.) are properly disposed of when they are no longer needed, even if an exception occurs. The using statement is a convenient way to handle disposable objects and avoids resource leaks.

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

The async and await keywords are used in C# to simplify asynchronous programming.

  • async: The async keyword is used to mark a method as asynchronous. It allows the method to use the await keyword and indicates that the method may have asynchronous operations.

  • await: The await keyword is used to pause the execution of an asynchronous method until a specific asynchronous operation completes. It allows the method to await the result of the operation without blocking the calling thread.

  1. What is boxing and unboxing in C#?
  • Boxing: Boxing is the process of converting a value type to a reference type. When a value type is boxed, a new object is created on the heap to store the value, and the value is copied into that object. Boxing is an implicit conversion.

  • Unboxing: Unboxing is the process of converting a boxed value type back to its original value type. It involves extracting the value from the object on the heap and storing it back into a value-type variable. Unboxing is an explicit conversion and can potentially throw an exception if the types don't match.

  1. What is the difference between a shallow copy and a deep copy?
  • Shallow copy: A shallow copy creates a new object and copies the values of the fields from the original object to the new object. If the field is a reference type, the reference is copied, not the actual object. As a result, both the original and copied objects point to the same memory location for reference-type fields.

  • Deep copy: A deep copy creates a new object and recursively copies the values of all fields, including reference-type fields. This ensures that the copied object has its own separate copy of the referenced objects. Modifying the copied object or the original object does not affect each other.

  1. Explain the concept of serialization in C#.

Serialization is the process of converting an object into a format that can be stored or transmitted and later reconstructed into an object. In C#, serialization allows objects to be converted into a stream of bytes, which can be saved to a file, sent over a network, or stored in a database. Deserialization is the reverse process, where the byte stream is converted back into an object.

C# provides different serialization techniques, such as Binary Serialization, XML Serialization (using attributes like [Serializable] and [XmlRoot]), and JSON Serialization (using libraries like Newtonsoft.Json). Serialization is commonly used for data persistence, interprocess communication, and distributed computing.

  1. How does exception handling work in C#?

Exception handling in C# allows you to catch and handle runtime errors, ensuring that your program gracefully handles exceptional situations. The core components of exception handling are:

  • try: The try block encloses the code that may throw an exception.
  • catch: The catch block catches and handles the thrown exception. It specifies the type of exception to catch and provides the code to handle the exception.
  • finally: The finally block contains code that is executed regardless of whether an exception is thrown or not. It is used for cleanup operations, such as closing files or releasing resources.

If an exception occurs within the try block, the execution jumps to the appropriate catch block. If a matching catch block is found, its code is executed. If no matching catch block is found, the exception is propagated up the call stack until it is handled or causes the program to terminate.

 

  1. Explain the concept of delegates and events in C#.
  • Delegates: Delegates in C# are type-safe function pointers that hold references to methods. They allow methods to be passed as parameters or stored in variables, making them suitable for implementing callback mechanisms. Delegates provide a way to achieve encapsulation and decoupling between the caller and the method being called.

  • Events: Events are a way to provide notifications of specific actions or state changes in a class. Events are based on delegates and provide a way for other classes or components to subscribe to and respond to those notifications. The class raising the event (publisher) defines the event and the delegate type, while other classes (subscribers) can subscribe to the event by providing event handler methods that match the delegate signature.

  1. What is the purpose of LINQ in C#?

LINQ (Language-Integrated Query) is a powerful feature in C# that provides a uniform and intuitive way to query and manipulate data from various data sources, such as collections, arrays, databases, XML, and more. It allows developers to write queries using a SQL-like syntax directly in the C# code, making it easier to express complex data retrieval and transformation operations.

LINQ queries are strongly typed and are verified at compile time. LINQ provides a set of standard query operators (methods) that can be used for filtering, sorting, grouping, joining, and projecting data. LINQ queries can be written using method syntax or query syntax (SQL-like syntax).

  1. What is the purpose of the lock keyword in C#?

The lock keyword is used for thread synchronization in C#. It ensures that only one thread can enter a specific section of code (a critical section) at a time, preventing concurrent access and potential race conditions. The lock keyword is typically used when multiple threads need to access shared resources.

The basic syntax is:


lock (lockObject)
{
    // Critical section
    // Code that needs to be accessed by only one thread at a time
}

The lockObject is an object used as a lock to control access to the critical section. If another thread attempts to enter the same critical section while it is locked by another thread, it will wait until the lock is released.