C# .net interview topics
C# .net interview topics
Class: A blueprint for creating objects. It defines properties (data) and methods
(behavior).
Object: An instance of a class. It represents a specific entity created from the class
blueprint.
Example:
csharp
CopyEdit
// Class definition
public class Car
{
public string Brand; // Property
public int Speed;
// Object creation
class Program
{
static void Main()
{
Car car = new Car(); // Object
car.Brand = "Toyota";
car.Speed = 120;
car.Drive();
}
}
2. Encapsulation
Encapsulation is the bundling of data (fields) and methods that operate on that data into a
single unit (class) while restricting access to some components.
Example:
csharp
CopyEdit
public class Person
{
private string name; // Encapsulated field
class Program
{
static void Main()
{
Person person = new Person();
person.Name = "John"; // Accessing through property
Console.WriteLine(person.Name);
}
}
3. Inheritance
Inheritance allows a class (child/derived class) to inherit properties and methods from another
class (parent/base class). It promotes code reusability.
Example:
csharp
CopyEdit
public class Animal
{
public void Eat()
{
Console.WriteLine("This animal eats food.");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Inherited method
dog.Bark(); // Dog's own method
}
}
4. Polymorphism
Example:
csharp
CopyEdit
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
Example:
csharp
CopyEdit
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("The animal makes a sound.");
}
}
class Program
{
static void Main()
{
Animal animal = new Dog();
animal.Speak(); // Output: The dog barks.
}
}
5. Abstraction
Abstraction is the process of hiding implementation details and exposing only the essential
features.
csharp
CopyEdit
public abstract class Shape
{
public abstract void Draw(); // Abstract method
}
Interface Example:
csharp
CopyEdit
public interface IShape
{
void Draw();
}
The choice between abstract classes and interfaces in C# depends on the design and use
case. Here's a detailed comparison to help you understand their differences and use cases:
1. Definition
Abstract Class: A class that can have both abstract methods (without
implementation) and concrete methods (with implementation). It is used to provide a
base class for other classes.
Interface: A contract that defines only method signatures, properties, events, or
indexers, with no implementation. A class implementing an interface must provide its
implementation.
2. Syntax
Abstract Class:
csharp
CopyEdit
public abstract class Shape
{
public abstract void Draw(); // Abstract method (no implementation)
public void Display() // Concrete method (with implementation)
{
Console.WriteLine("This is a shape.");
}
}
Interface:
csharp
CopyEdit
public interface IShape
{
void Draw(); // No implementation allowed
}
3. Key Differences
4. Usage Examples
csharp
CopyEdit
public abstract class Animal
{
public abstract void Speak(); // Abstract method
public void Sleep() // Concrete method
{
Console.WriteLine("Sleeping...");
}
}
class Program
{
static void Main()
{
Animal dog = new Dog();
dog.Speak(); // Output: Dog barks.
dog.Sleep(); // Output: Sleeping...
}
}
Interface Example:
csharp
CopyEdit
public interface IVehicle
{
void Start();
void Stop();
}
class Program
{
static void Main()
{
IVehicle car = new Car();
car.Start(); // Output: Car is starting...
car.Stop(); // Output: Car is stopping...
}
}
1. You need to provide a base class with common functionality for related classes.
2. You want to include both abstract methods (to be implemented by derived classes)
and concrete methods (to provide shared logic).
3. You want to define fields or state that will be shared among derived classes.
You can combine both for more flexible designs. For example:
csharp
CopyEdit
public interface IWalkable
{
void Walk();
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Dog eats food.
dog.Walk(); // Output: Dog walks.
}
}
Summary
These three keywords are used in the context of method overriding in C#, enabling
polymorphism and defining how methods can be overridden or restricted.
1. Virtual
Key Points:
Example:
csharp
CopyEdit
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Display method in BaseClass.");
}
}
class Program
{
static void Main()
{
BaseClass obj = new DerivedClass();
obj.Display(); // Output: Display method in DerivedClass.
}
}
2. Override
The override keyword is used in a derived class to provide a new implementation for
a virtual or abstract method defined in the base class.
The overridden method in the derived class must have the same signature as the
method in the base class.
Key Points:
Example:
csharp
CopyEdit
public class BaseClass
{
public virtual void Greet()
{
Console.WriteLine("Hello from BaseClass!");
}
}
class Program
{
static void Main()
{
BaseClass obj = new DerivedClass();
obj.Greet(); // Output: Hello from DerivedClass!
}
}
3. Sealed
Key Points:
Example:
csharp
CopyEdit
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Display method in BaseClass.");
}
}
class Program
{
static void Main()
{
DerivedClass obj = new DerivedClass();
obj.Display(); // Output: Display method in DerivedClass.
}
}
Real-World Analogy
Delegates and events are fundamental concepts in C#, enabling callback mechanisms,
communication, and event-driven programming.
1. Delegates
Definition
Key Features:
Syntax
Declare a delegate:
csharp
CopyEdit
public delegate void MyDelegate(string message); // Declaring a delegate
Example:
csharp
CopyEdit
// Delegate Declaration
public delegate void PrintDelegate(string message);
class Program
{
public static void PrintMessage(string msg)
{
Console.WriteLine(msg);
}
// Multicast Delegate
del += PrintUppercaseMessage; // Add another method
del("Hello, Delegates!");
// Output:
// Hello, Delegates!
// HELLO, DELEGATES!
}
}
2. Events
Definition
Key Features:
Declare an event:
csharp
CopyEdit
public delegate void NotifyDelegate(string message);
public class Publisher
{
public event NotifyDelegate OnNotify; // Declaring an event
}
Example:
csharp
CopyEdit
// Step 1: Declare a delegate
public delegate void Notify(string message);
class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
Events can use multicast delegates, meaning multiple subscribers can handle a single event.
Example:
csharp
CopyEdit
public delegate void Notify(string message);
class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
// Multiple handlers for the same event
publisher.OnNotify += subscriber.ShowMessage;
publisher.OnNotify += subscriber.AnotherMessageHandler;
publisher.NotifySubscribers("Event raised!");
// Output:
// Subscriber 1 received: Event raised!
// Subscriber 2 received: Event raised!
}
}
Summary
1. Method Overloading
Method overloading allows multiple methods in the same class to have the same name but
different parameters (by type, number, or both).
Key Features:
Example:
csharp
CopyEdit
class Calculator
{
public int Add(int a, int b)
{
return a + b; // Adds two integers
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
2. Method Overriding
Method overriding allows a derived class to provide a new implementation for a method
that is already defined in its base class.
Key Features:
Requires inheritance.
The base class method must be marked as virtual, abstract, or override.
The derived class method must use the override keyword.
It is an example of runtime polymorphism (also known as dynamic polymorphism).
Example:
csharp
CopyEdit
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound.");
}
}
class Program
{
static void Main()
{
Animal animal = new Animal();
animal.Speak(); // Output: Animal makes a sound.
The method signature (name, parameters, return type) must be the same as in the base
class.
The base method must be declared as virtual or abstract to allow overriding.
The overridden method in the derived class must use the override keyword.
The base method implementation can still be accessed using the base keyword.
Defining multiple methods with the same Redefining a method from the base
Definition
name but different parameter lists. class in the derived class.
Parameters Must differ in type, number, or order. Must have the same signature.
Increases method flexibility for different Allows a derived class to change the
Purpose
input types or parameter counts. base class behavior.
Combined Example
csharp
CopyEdit
class Parent
{
public virtual void Show()
{
Console.WriteLine("Parent's Show method");
}
}
// Overloading
public void Show(string message)
{
Console.WriteLine($"Child's overloaded Show method: {message}");
}
}
class Program
{
static void Main()
{
Parent parent = new Parent();
parent.Show(); // Output: Parent's Show method
Summary
In C#, collections are used to store and manipulate groups of related objects efficiently.
Here's a breakdown of commonly used generic collections in .NET, including List<T>,
Dictionary<K,V>, HashSet<T>, Queue<T>, and Stack<T>.
1. List<T>
Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // Add an element
numbers.Insert(1, 10); // Insert an element at index 1
2. Dictionary<K, V>
Definition: A generic collection that stores key-value pairs. Each key must be unique, and
keys are used to access the associated values.
Key Features:
o Fast lookups using keys.
o Keys must be unique, but values can be duplicate.
o Does not maintain the order of elements.
Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> students = new Dictionary<int, string>
{
{ 1, "Alice" },
{ 2, "Bob" },
{ 3, "Charlie" }
};
3. HashSet<T>
Definition: A collection that stores unique elements and offers high-performance lookups.
Key Features:
o Does not allow duplicate elements.
o Does not maintain the order of elements.
o Optimized for set operations like union, intersection, and difference.
Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set = new HashSet<int> { 1, 2, 3, 4 };
4. Queue<T>
Definition: A first-in, first-out (FIFO) collection of elements. Items are added at the back and
removed from the front.
Key Features:
o Elements are processed in the order they were added.
o Commonly used for sequential processing tasks.
Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Queue<string> queue = new Queue<string>();
queue.Enqueue("Task1");
queue.Enqueue("Task2");
queue.Enqueue("Task3");
Definition: A last-in, first-out (LIFO) collection of elements. Items are added to and removed
from the top of the stack.
Key Features:
o Elements are processed in reverse order (last added is the first removed).
o Commonly used for backtracking scenarios like navigating back in a browser.
Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Stack<string> stack = new Stack<string>();
stack.Push("Page1");
stack.Push("Page2");
stack.Push("Page3");
Comparison Table
Collection Allows Duplicates Maintains Order Key Feature
Le
LINQ stands for Language Integrated Query, a powerful feature in C# that enables
querying data in a consistent, readable, and type-safe manner, regardless of the data source
(e.g., collections, databases, XML, etc.). It allows you to write queries directly in C# without
requiring SQL, XPath, or other domain-specific languages.
1. Unified Query Syntax: Query various data sources (collections, databases, XML) using the
same syntax.
2. Strongly Typed: LINQ queries are type-checked at compile time, reducing runtime errors.
3. Readable and Declarative: LINQ syntax is similar to SQL, making it easier to understand.
4. Deferred Execution: Many LINQ operations are executed only when the result is iterated
(e.g., using foreach).
5. Integration with .NET: Fully integrated into the .NET framework and works seamlessly with
C# collections and other data sources.
LINQ Syntax
1. Where (Filtering)
2. Select (Projection)
3. OrderBy (Sorting)
4. GroupBy (Grouping)
5. Join (Joining)
6. Aggregate (Aggregations)
Examples
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// Query Syntax
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 35 }
};
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
3. LINQ to SQL
4. LINQ to XML
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
string xml = @"<Books>
<Book><Title>C#
Programming</Title><Price>500</Price></Book>
<Book><Title>LINQ
Basics</Title><Price>300</Price></Book>
</Books>";
Advantages of LINQ
Disadvantages
1. Can sometimes be less performant than raw SQL for complex queries.
2. Debugging LINQ expressions can be challenging.
3. Limited control over SQL queries generated in LINQ-to-SQL.
When to Use LINQ?
Let me know if you'd like specific examples or a deeper dive into any of these concepts!
IEnumerable vs IQueryable:-
Both IEnumerable and IQueryable are interfaces in C# used for data querying and
manipulation. However, they have significant differences in terms of execution,
performance, and use cases.
1. IEnumerable
Namespace: System.Collections
Definition: It is used to iterate over a collection of objects, such as arrays, lists, or other in-
memory data.
Key Characteristics
Use Cases
csharp
CopyEdit
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// IEnumerable
IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0); //
Filters in-memory
2. IQueryable
Namespace: System.Linq
Definition: It is used for querying data sources that implement LINQ providers, such as
databases, and translates LINQ queries into specific queries (e.g., SQL for databases).
Key Characteristics
1. Query Execution on Data Source: Executes the query on the server-side (e.g., SQL
Server).
2. Deferred Execution: Like IEnumerable, queries are executed when accessed.
3. Efficient Filtering: Only the required data is fetched from the data source, reducing
memory usage.
4. Used in LINQ to SQL/EF: Commonly used for querying remote databases through
LINQ to SQL or Entity Framework.
5. Complex Query Translation: Converts LINQ queries to SQL or equivalent for the
underlying data source.
Use Cases
Best for querying large datasets stored in databases or other external sources.
Preferred when working with LINQ to SQL or Entity Framework to optimize data
retrieval.
csharp
CopyEdit
using System;
using System.Linq;
using System.Data.Entity;
class Program
{
static void Main()
{
using (var context = new MyDbContext())
{
// IQueryable
IQueryable<Customer> customersFromPune = context.Customers
.Where(c => c.City == "Pune"); // Filters on the database
server
Key Differences
When to Use
Use IEnumerable:
o When working with in-memory collections.
o For small datasets where performance is not a concern.
o In cases where the data is already loaded.
Use IQueryable:
o When querying large datasets from databases.
o When working with Entity Framework or LINQ-to-SQL.
o For better performance and efficiency in data retrieval.
Practical Comparison
csharp
CopyEdit
IEnumerable<Customer> customers = context.Customers.ToList();
var filteredCustomers = customers.Where(c => c.City == "Pune"); // Entire
table loaded into memory
csharp
CopyEdit
IQueryable<Customer> customers = context.Customers;
var filteredCustomers = customers.Where(c => c.City == "Pune"); // Filters
at the database level
Key Takeaways
Let m