C#

 

. Explain the difference between abstract classes and interfaces.

  • Answer: Abstract classes can have both abstract and implemented members, support fields, and constructors. Interfaces can only declare methods, properties, events, and indexers without implementation (prior to C# 8.0). Starting with C# 8.0, interfaces can have default implementations.

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

  • Answer: The using statement ensures that IDisposable objects are disposed of correctly, releasing unmanaged resources deterministically.

c. How does garbage collection work in .NET?

  • Answer: The garbage collector automatically manages memory by reclaiming memory occupied by objects that are no longer referenced in the application, reducing memory leaks and optimizing resource usage.

d. Explain the concept of async and await.

  • Answer: async marks a method as asynchronous, allowing it to run without blocking the calling thread. await is used within async methods to pause execution until the awaited task completes, enabling non-blocking operations.

e. What are delegates and how are they used?

  • Answer: Delegates are type-safe method references that allow methods to be passed as parameters. They are commonly used for implementing events and callback methods.

Value type vs Reference type

In C#, value types and reference types are two primary categories of types that determine how data is stored and accessed in memory. Here's a detailed comparison:

Key Differences

Aspect

Value Type

Reference Type

Storage

Stored on the stack

Stored on the heap (reference on stack)

Data Containment

Contains the actual data

Contains a reference to the data

Assignment

Creates a copy of the value

Copies the reference to the same object

Performance

Faster (stack operations)

Slower (heap operations)

Garbage Collection

Not applicable (stack is automatically managed)

Managed by the garbage collector

Effect of Changes

Independent after assignment

Affects all references to the same object

 

Practical Implications

When to Use Value Types

  • When the data is small, simple, and short-lived.
  • For scenarios where copying is inexpensive.
  • Example: Use structs for points, coordinates, or primitive data.

When to Use Reference Types

  • When the data is large, complex, or long-lived.
  • For scenarios where sharing and modification of the same instance are required.
  • Example: Use classes for entities, collections, or objects representing behavior.

In programming, particularly in C#, the heap and stack are two types of memory used for storing data. Each has different characteristics and serves distinct purposes. Here's a breakdown:

Key Differences Between Stack and Heap

Aspect

Stack

Heap

Type of Memory

Static memory

Dynamic memory

Storage

Primitive data types, references

Objects, large data structures

Allocation/Deallocation

Automatic (LIFO)

Manual (new keyword) and garbage collected

Access Speed

Faster

Slower

Size

Smaller, fixed

Larger, flexible

Lifetime

Tied to function scope

Managed by garbage collector

Usage

Local variables, function calls

Objects, dynamic data

                                   

Practical Implications

  • Use stack for lightweight, short-lived variables.
  • Use heap for complex objects or data that must persist beyond a single function call.

C# Class types

C# supports several types of classes, each serving specific purposes in object-oriented programming. Here’s an overview of the main class types in C#:


1. Regular Class

A regular class is the most common type of class, which can be instantiated to create objects. It can include fields, properties, methods, and constructors.

Example:

Csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

2. Static Class

A static class is a class that cannot be instantiated. It can only contain static members and is used for utility or helper methods.

Characteristics:

  • Declared using the static keyword.
  • Cannot contain instance constructors, methods, or properties.

Example:

Csharp
public static class MathHelper
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

Usage:

Csharp
int result = MathHelper.Add(5, 10);

3. Abstract Class

An abstract class is a class that cannot be instantiated directly. It can contain abstract methods (without implementation) and concrete methods (with implementation).

Example:

Csharp
public abstract class Shape
{
    public abstract double GetArea(); // Abstract method
    public void Display() // Concrete method
    {
        Console.WriteLine("This is a shape.");
    }
}
 
public class Circle : Shape
{
    public double Radius { get; set; }
    public override double GetArea() => Math.PI * Radius * Radius;
}

Usage:

Csharp
Shape shape = new Circle { Radius = 5 };
Console.WriteLine(shape.GetArea());

4. Sealed Class

A sealed class is a class that cannot be inherited. It is declared using the sealed keyword and is useful for preventing further extension.

Example:

Csharp
public sealed class FinalClass
{
    public void DisplayMessage()
    {
        Console.WriteLine("This class cannot be inherited.");
    }
}

5. Partial Class

A partial class allows its definition to be split across multiple files. All parts are combined into one class at compile time.

Example: File 1: Person1.cs

Csharp
public partial class Person
{
    public string Name { get; set; }
}

File 2: Person2.cs

Csharp
public partial class Person
{
    public int Age { get; set; }
}

Usage:

Csharp
Person person = new Person { Name = "John", Age = 30 };

6. Nested Class

A nested class is a class defined within another class. It is useful for logically grouping classes that are only used by the containing class.

Example:

Csharp
public class OuterClass
{
    public class InnerClass
    {
        public void Display()
        {
            Console.WriteLine("Inner class method.");
        }
    }
}

Usage:

Csharp
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.Display();

7. Generic Class

A generic class allows type parameters to define the class, enabling code reusability with different data types.

Example:

Csharp
public class GenericClass<T>
{
    public T Data { get; set; }
    public void Display()
    {
        Console.WriteLine($"Data: {Data}");
    }
}

Usage:

Csharp
GenericClass<int> obj = new GenericClass<int> { Data = 123 };
obj.Display();

8. Record Class (C# 9 and later)

A record class is a specialized class primarily used for immutable data models. It provides value-based equality by default.

Example:

Csharp
public record Person(string Name, int Age);

Usage:

Csharp
var person1 = new Person("John", 30);
var person2 = new Person("John", 30);
 
Console.WriteLine(person1 == person2); // True (value equality)

 

 

What is Object-Oriented Programming (OOP)? Explain its principles.

OOP is a programming paradigm based on the concept of "objects," which can contain data in the form of fields (properties) and code in the form of methods.

The four main principles of OOP are:

  1. Encapsulation: Bundling data and methods into a class and restricting access using access modifiers.
  2. Inheritance: Allowing a class to inherit properties and methods from another class.
  3. Polymorphism: Using a single interface to represent different underlying forms (e.g., method overriding and overloading).
  4. Abstraction: Hiding implementation details and exposing only the essential features.

What is the difference between a class and an object?

  • A class is a blueprint or template that defines the structure and behavior of objects. Example: class Car { }
  • An object is an instance of a class that is created in memory. Example: Car myCar = new Car();

What is the difference between method overloading and method overriding?

Aspect

Method Overloading

Method Overriding

Definition

Multiple methods in the same class with the same name but different parameters.

A derived class redefines a method of its base class.

Compile-time vs Runtime

Compile-time polymorphism.

Runtime polymorphism.

Access Modifier

Methods can have any access modifier.

The overriding method must be public, protected, or less restrictive.

Example

void Add(int a, int b)
void Add(double a, double b)

virtual void Display()
override void Display()

What is an abstract class? How is it different from an interface?

An abstract class is a class that cannot be instantiated and may contain abstract methods (without implementation) and concrete methods (with implementation).

Differences:

Aspect

Abstract Class

Interface

Implementation

Can have concrete methods with implementation.

Only method signatures (until C# 8.0, now it can have default methods).

Inheritance

Supports single inheritance.

Supports multiple inheritance.

Access Modifiers

Can have fields with access modifiers.

Cannot have fields; all members are public by default.

Example

abstract class Shape { abstract void Draw(); }

interface IShape { void Draw(); }

What is the difference between virtual, override, and new keywords in C#?

  • virtual: Used in the base class to indicate that a method can be overridden in a derived class.
  • override: Used in the derived class to provide a new implementation for a virtual or abstract method in the base class.
  • new: Used in the derived class to hide a method from the base class if it is not virtual.

What is the difference between encapsulation and abstraction?

Aspect

Encapsulation

Abstraction

Definition

Hides the internal state of an object and provides controlled access using access modifiers.

Hides implementation details and shows only essential features.

Implementation

Achieved through classes, properties, and access modifiers (private, public).

Achieved through abstract classes and interfaces.

Example

private int age; public int Age { get; set; }

abstract class Shape { abstract void Draw(); }

What is the difference between this and base keywords in C#?

  • this: Refers to the current instance of the class.
  • base: Refers to the parent class of the current class and is used to access base class members.

Can you explain access modifiers in C#?

 C# provides the following access modifiers to control the visibility of class members:

  • public: Accessible from anywhere.
  • private: Accessible only within the containing class.
  • protected: Accessible within the containing class and derived classes.
  • internal: Accessible within the same assembly.
  • protected internal: Accessible within the same assembly or derived classes.
  • private protected: Accessible within the containing class or derived classes in the same assembly.

What is the difference between shallow copy and deep copy?

  • Shallow Copy: Copies the reference of the objects. Changes in the copied object affect the original object.
  • Deep Copy: Copies the entire object along with its dependencies. Changes in the copied object do not affect the original object.

 

 

What is the difference between Task and Thread in C#?

·       Thread:

    • Represents a single thread of execution in the operating system.
    • Manually managed by the developer.
    • Requires more resources to create and manage.

·       Task:

    • Represents an abstraction of asynchronous operations.
    • Optimized for parallel and asynchronous operations.
    • Uses the thread pool for efficiency.

What is the difference between ref and out parameters in C#?

  • ref:
    • The variable must be initialized before being passed to the method.
    • Allows the method to read and modify the variable.
  • out:
    • The variable does not need to be initialized before being passed.
    • The method must assign a value to the out parameter before returning.

Explain the concept of boxing and unboxing in C#.

  • Boxing: The process of converting a value type (like int) to a reference type (like object).
  • Unboxing: The process of converting a reference type (like object) back to a value type.

What is a delegate in C#?

A delegate is a type that represents references to methods with a particular parameter list and return type. It allows methods to be passed as parameters.

Csharp
public delegate void GreetDelegate(string name);
 
public void Greet(string name)
{
    Console.WriteLine($"Hello, {name}!");
}
 
GreetDelegate greetDelegate = new GreetDelegate(Greet);
greetDelegate("John");

 

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

The using statement is used to define a scope for objects that implement IDisposable. It ensures that the object's Dispose() method is called when the scope is exited, even if an exception occurs. This is useful for releasing resources like file handles, database connections, etc.

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

  • String is immutable. When you modify a string, a new string is created in memory.
  • StringBuilder is mutable and designed for scenarios where you need to make a lot of modifications to a string, as it doesn’t create a new object each time you modify it.

What is the difference between == and Equals() in C#?

  • ==: This is a comparison operator. For value types, it compares the actual values, and for reference types, it checks if the two references point to the same memory location.
  • Equals(): This is a method defined in the Object class that can be overridden. It compares the actual content of the objects, which is useful for reference types if you want to compare values instead of memory addresses.

 LINQ 

LINQ (Language Integrated Query) in C# is a powerful tool that allows querying and manipulating data from different sources like collections, databases, XML, etc., using a consistent syntax.

There are two styles of LINQ syntax in C#:


  • Where: Filters elements based on a condition.
    • var adults = people.Where(p => p.Age >= 18);
  • Select: Projects each element into a new form.
    • var names = people.Select(p => p.Name);
  • OrderBy: Sorts elements in ascending order.
    • var sorted = people.OrderBy(p => p.Name);
  • Join: Joins two sequences based on keys.

var result = people.Join(departments,

                         person => person.DeptId,

                         dept => dept.Id,

                         (person, dept) => new { person.Name, dept.DepartmentName });

  • First: Returns the first element.
  • FirstOrDefault: Returns the first element or default value.
  • Single: Returns a single element (throws exception if not exactly one).
  • SingleOrDefault: Returns a single element or default value.

 Difference Between IQueryable and IEnumerable

Both IQueryable and IEnumerable are used to work with collections in C#, but they differ in their functionality, execution model, and use cases. Here's a detailed comparison:


Aspect

IQueryable

IEnumerable

Namespace

System.Linq

System.Collections or System.Collections.Generic

Execution

Deferred execution (queries are translated into SQL or other expressions and executed on demand).

Immediate execution (data is loaded into memory before processing).

Primary Use Case

Suitable for querying data sources like databases (e.g., LINQ-to-SQL, LINQ-to-Entities).

Suitable for in-memory collections like lists, arrays, and other enumerable objects.

Performance

More efficient for large datasets as it performs query execution on the server side (e.g., SQL).

May have performance issues with large datasets as all data is loaded into memory before processing.

Query Translation

Translates LINQ queries into provider-specific expressions (e.g., SQL for EF Core).

Does not translate queries; works directly with in-memory data.

Deferred Query Execution

Yes, queries are executed when enumerated (e.g., when using ToList() or a foreach loop).

Can also be deferred, but operates on in-memory data only.

Data Source

Works with data sources like databases, remote APIs, or other queryable providers.

Works with in-memory data sources such as lists, arrays, and collections.

Filtering

Filters and transformations are applied at the database or data source level, reducing data transfer.

Filters and transformations are applied in memory after loading the data.

Lazy Evaluation

Executes queries on demand, meaning only the required data is retrieved.

Executes queries in memory, requiring all data to be loaded first.


Example Use Cases

IQueryable Example

Csharp

using System.Linq;

 

IQueryable<Product> products = dbContext.Products; // From Entity Framework

var expensiveProducts = products.Where(p => p.Price > 100); // Query is not executed yet

var result = expensiveProducts.ToList(); // Query executes here, retrieving only filtered data from the database

IEnumerable Example

Csharp

using System.Collections.Generic;

 

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

var evenNumbers = numbers.Where(n => n % 2 == 0); // In-memory filtering

foreach (var num in evenNumbers)

{

    Console.WriteLine(num); // Output: 2, 4

}


Key Considerations

  • Use IQueryable when working with databases or remote data sources, as it optimizes query performance by executing filtering and transformations at the data source level.
  • Use IEnumerable for in-memory collections, where all the data is already loaded into memory, and further filtering is applied locally.

By understanding these differences, you can make informed decisions about which to use for better performance and maintainability.

 

 

Comments

Popular posts from this blog

SQL

C# operations

.NET Web API interview questions