LogIn
I don't have account.

C# Interview Questions and Answers I

Code Crafter
142 Views

C# is the most popular general-purpose programming language and was developed by Microsoft in 2000. Known for its robustness and flexibility, C# supports object-oriented programming and is widely used for building a variety of applications.

In this blog, we’ve compiled the top C# interview questions and answers designed for both freshers and experienced professionals. The questions cover a wide range of topics, including core C# concepts, object-oriented programming (OOP), multithreading, exception handling, design patterns, the .NET framework and more. This comprehensive guide will surely help you prepare C# interview and boost your skills in C# concept.

What is C#?

C# is a modern, object-oriented and type-safe programming language developed by Microsoft as part of its .NET initiative in the early 2000s. It is designed for building a wide range of applications, including web, desktop, mobile, cloud-based and enterprise software.

C# is very close to C/C++ and Java programming languages. C# supports features like garbage collection, LINQ, asynchronous programming, and strong type checking, making development faster and less error-prone.

It runs on the .NET platform, which provides a large standard library and runtime environment for building and running applications.

What is Common Language Runtime (CLR)?

The Common Language Runtime (CLR) is the core runtime engine of the .NET Framework. It provides a managed execution environment for .NET applications by handling key aspects such as:

  • Memory management
  • Garbage collection
  • Exception handling
  • Security
  • Thread management
  • Code verification etc

CLR allows code written in different .NET-supported languages (like C#, VB.NET, or F#) to run in a unified environment. It converts the compiled code (Intermediate Language or IL) into machine code through a process called Just-In-Time (JIT) compilation.

Overall, the CLR ensures that .NET applications run efficiently, securely and interact seamlessly across different programming languages.

What is inheritance in C#?

Inheritance is a fundamental concept in Object-Oriented Programming (OOP), where a class (called a child class or derived class) can inherit properties, methods, and behaviors from another class (called the parent class or base class). This allows the child class to reuse code from the parent class without having to re-implement it.

class BaseClass
{
    public void DisplayMessage()
    {
        Console.WriteLine("Hello from BaseClass");
    }
}
class DerivedClass : BaseClass
{
    public void Show()
    {
        Console.WriteLine("Hello from DerivedClass");
    }
}

Multiple Inheritance Not supported directly for classes, but can be achieved via interfaces

Why does C# not support multiple inheritance?

C# does not support multiple inheritance (where a class can inherit from more than one base class) to avoid the complexity and ambiguity.

  • Ambiguity: Multiple inheritance can lead to situations where a class could inherit the same method or property from more than one parent, causing ambiguity.
  • Complexity: It can make the class structure more complex and difficult to maintain.

Multiple inheritance can lead to issues like the Diamond Problem, where a class inherits from two classes that have a method with the same name. This can cause confusion about which method should be called.

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

In C#, both arrays and ArrayLists are used to store a collection of data, but they have significant differences in terms of functionality, performance, and type safety.

1. Type of Collection
  • Array : An array is strongly-typed collection that can hold elements of a specific data type. Example: int[] numbers = new int[5];
  • ArrayList : An ArrayList can store elements of any data type (not strongly typed). Example : ArrayList list = new ArrayList();
2. Size
  • Array: Size is fixed at the time of declaration and cannot be changed after creation.
  • ArrayList: The size is dynamic and can grow or shrink as elements are added or removed.
3. Type Safety
  • Array: Type-safe, meaning it can only store elements of a specific type (e.g. int[], string[]).
  • ArrayList: Not type-safe; it stores elements as objects, which can be of any type (e.g., ArrayList list = new ArrayList(); can store int, string, or any other object type).
4. Performance
  • Array: Faster and more memory-efficient for fixed-size collections because it doesn't require resizing.
  • ArrayList: Slightly slower due to the overhead of resizing the array internally when elements are added beyond its capacity.
5. Usage
  • Array: Ideal when the size of the collection is known in advance and does not change.
  • ArrayList: Useful when the size of the collection can change dynamically and the type of elements is not strictly defined.
5. Indexing
  • Both Array and ArrayList support indexing (i.e. accessing elements using an index like arr[0] or list[0]), but the underlying storage mechanism differs.

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

In C#, both class and struct are user-defined types that encapsulate data and behavior, but they differ significantly in memory management, performance and capabilities.

A class is a reference type stored on the heap. When you assign a class object to a variable, you're assigning a reference to that memory location. Classes can include fields, properties, methods, events and support advanced object-oriented features like inheritance, polymorphism and abstraction. They are ideal for complex data models and shared objects.

A struct is a value type typically stored on the stack (unless boxed). Structs are best for small, lightweight objects that represent simple data. Unlike classes, structs do not support inheritance (except interface implementation), cannot be abstract and have limited constructor usage (no parameterless constructors allowed).

While both can contain similar members, use struct for performance-critical, short-lived, and immutable data, and class for scalable, shared and extensible object models.

What Does "No Parameterless Constructors Allowed" Mean in Structs?

In C#, structs cannot define their own parameter less (default) constructors - unlike classes.

For classes, you can define a constructor with no parameters

class MyClass {
    public MyClass() {
        // Custom logic
    }
}

But for structs, C# automatically provides a default parameter less constructor, and you cannot override or define your own

struct MyStruct {
    // ❌ This will cause a compile-time error
    // public MyStruct() { }
    public MyStruct(int x) {
        this.X = x;
    }
    public int X;
}

Because

  • The .NET runtime ensures all value types (structs) are automatically initialized to default values (e.g. 0, false, null) when declared.
  • Letting developers define a custom parameter less constructor could break this guarantee and create inconsistency.

What is enum in C#?

In C#, an enumeration (enum) is a special value type used to define a set of named constants. It makes your code more readable and manageable by replacing numeric literals with descriptive names.

enum DayOfWeek {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}
  • By default, the underlying type of each enum member is int, and the first member starts at 0, increasing by 1.
  • You can explicitly set values
enum DayOfWeek {
    None = 0,
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday =7
}

What is the difference between ref and out keywords?

The ref keyword in C# is used to pass a parameter by reference, and the variable must be initialized before it’s passed to the method. It allows the method to modify the value. On the other hand, the out keyword also passes by reference, but the variable doesn't need to be initialized first. The method must assign a value to the out parameter before it returns. So, ref is for both input and output, while out is mainly for output.

What are Properties in C#?

In C#, properties are members of a class or struct that allow you to access and modify private fields in a controlled way. They serve as a bridge between the private data within a class and the outside world, enabling you to retrieve (get) or update (set) the value of a field safely

Properties are similar to methods but are accessed like fields. They consist of two parts

  • Getters: Retrieve the value of a private field.
  • Setters: Assign a value to a private field.
class Person
{
    private string name;
    public string Name   // Property
    {
        get { return name; }  // Getter
        set { name = value; }  // Setter
    }
}

What are the types of Properties in c#?

In C#, there are several types of properties based on their functionality and usage. These include

  • Auto-Implemented Properties
  • Read-Only Properties
  • Write-Only Properties
  • Expression-Bodied Properties
  • Indexers
  • Static Properties
  • Computed (Calculated) Properties
  • Backing Fields (Manually Implemented Properties)
  • Init-only Properties (introduced in C# 9)

Each type serves a specific purpose in controlling how data is accessed, modified, and stored within a class. To read more about Properties in c# C# Properties Questions and Answers

What are Generics in C#?

Generics in C# are a powerful feature that allow developers to design classes, interfaces, methods and delegates with a placeholder for the data type. This helps achieve type-safety, code reusability, and performance improvement by avoiding unnecessary type casting and boxing/unboxing.

public class GenericList<T>
{
    private T[] items;
    private int count;
    public void Add(T item)
    {
        // Add item logic
    }
    public T Get(int index)
    {
        return items[index];
    }
}
GenericList<float> list1 = new GenericList<float>();
GenericList<string> list2 = new GenericList<string>();
GenericList<MyClass> list3 = new GenericList<MyClass>();

In each of the above cases, T is replaced with the specified type (float, string, MyClass) at compile-time.

When should we use Generics?

You should use Generics in C# when

  • Type Safety Is Needed :- Use generics to catch type-related errors at compile time rather than runtime. This prevents invalid casts and unexpected exceptions.
  • Code Reusability : If you find yourself writing the same logic for multiple data types, generics let you write the logic once and apply it to any type.
  • Avoiding Boxing and Unboxing :- With generics, value types (like int, float, bool) don’t need to be boxed when used in collections like List<T>, which improves performance.
  • Building Strongly-Typed Collections : Generics help you create type-specific collections like List<string> or Dictionary<int, string>, which prevent incorrect data from being added.
  • Creating Reusable Methods or Classes : For example, a method that swaps two values of any type:
    public void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }
  • Improved Performance : Less casting and fewer runtime checks mean faster execution, especially in high-performance or large-scale applications.