C# & ASP.NET Topic
C# & .NET Interview Questions Part 1
1. What is the difference between == and .Equals() in C#?
Answer:
-
==is an operator that compares references for reference types and values for value types -
.Equals()is a virtual method that typically compares object content
csharp
string a = "hello";
string b = "hello";
string c = new string("hello".ToCharArray());
Console.WriteLine(a == b); // True - same content
Console.WriteLine(a.Equals(b)); // True - same content
Console.WriteLine(a == c); // True - string interning
Console.WriteLine(a.Equals(c)); // True - same content
object obj1 = a;
object obj2 = c;
Console.WriteLine(obj1 == obj2); // False - different references
Console.WriteLine(obj1.Equals(obj2)); // True - same content
2. What are the differences between abstract class and interface?
Answer:
-
Abstract Class: Can have implementation, constructors, fields, access modifiers
-
Interface: Only method signatures, properties, events, indexers (C# 8.0+ can have default implementations)
csharp
abstract class Animal {
protected string Name; // Fields allowed
public Animal(string name) { Name = name; } // Constructor
public abstract void MakeSound(); // Abstract method
public void Sleep() { Console.WriteLine("Sleeping"); } // Concrete method
}
interface IFlyable {
void Fly(); // Only signature
int MaxAltitude { get; } // Property
}
3. Explain the async and await keywords in C#.
Answer:
-
asyncmarks a method as asynchronous -
awaitsuspends method execution until the awaited task completes -
Doesn't block the thread - uses continuation
csharp
public async Task<string> DownloadDataAsync(string url)
{
using var client = new HttpClient();
string data = await client.GetStringAsync(url); // Non-blocking
return data.ToUpper();
}
// Usage
var result = await DownloadDataAsync("https://api.example.com/data");
4. What is Dependency Injection and why is it important?
Answer:
DI is a design pattern where objects receive their dependencies from external sources rather than creating them internally.
Benefits:
-
Loose coupling
-
Testability
-
Maintainability
-
Flexibility
csharp
// Without DI
public class OrderService {
private EmailService _emailService = new EmailService(); // Tight coupling
}
// With DI
public class OrderService {
private readonly IEmailService _emailService;
public OrderService(IEmailService emailService) { // Dependency injected
_emailService = emailService;
}
}
5. What are the different types of memory in .NET?
Answer:
-
Stack: Value types, method parameters, references
-
Heap: Reference type objects, static variables
-
Generation 0: Short-lived objects
-
Generation 1: Buffer between Gen 0 and Gen 2
-
Generation 2: Long-lived objects
-
Large Object Heap: Objects > 85KB
6. Explain the using statement in C#.
Answer:
The using statement ensures proper disposal of IDisposable objects by calling Dispose() automatically.
csharp
// Automatically calls Dispose() even if exception occurs
using (var stream = new FileStream("file.txt", FileMode.Open))
{
// Work with stream
}
// C# 8.0+ using declaration
using var stream = new FileStream("file.txt", FileMode.Open);
// Automatically disposed at end of scope
7. What is the difference between StringBuilder and string?
Answer:
-
string: Immutable - each operation creates new string
-
StringBuilder: Mutable - efficient for multiple append operations
csharp
// Inefficient with many operations
string result = "";
for (int i = 0; i < 1000; i++) {
result += i; // Creates new string each time
}
// Efficient with StringBuilder
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.Append(i); // Modifies internal buffer
}
string finalResult = sb.ToString();
8. What are Delegates and Events in C#?
Answer:
-
Delegate: Type-safe function pointer
-
Event: Encapsulated delegate following publisher-subscriber pattern
csharp
public delegate void Notify(string message); // Delegate
public class Publisher {
public event Notify OnNotify; // Event
public void DoWork() {
OnNotify?.Invoke("Work completed"); // Raise event
}
}
public class Subscriber {
public void HandleNotification(string message) {
Console.WriteLine($"Received: {message}");
}
}
9. What is Entity Framework and what are its different approaches?
Answer:
EF is an ORM (Object-Relational Mapper) for .NET.
Approaches:
-
Database First: Generate models from existing database
-
Model First: Design models in EF designer, generate database
-
Code First: Write model classes, EF creates database
csharp
// Code First example
public class Product {
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class AppDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
10. What is LINQ and what are its types?
Answer:
LINQ (Language Integrated Query) allows querying data in C#.
Types:
-
LINQ to Objects: Query collections in memory
-
LINQ to SQL: Query SQL databases
-
LINQ to Entities: Query via Entity Framework
-
LINQ to XML: Query XML documents
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 };
// Query syntax
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
// Method syntax
var evenNumbers = numbers.Where(n => n % 2 == 0);
11. What is Garbage Collection in .NET?
Answer:
Automatic memory management that:
-
Allocates objects on heap
-
Identifies unused objects
-
Reclaims memory
Generations:
-
Gen 0: New objects, frequent collection
-
Gen 1: Survived Gen 0 collection
-
Gen 2: Long-lived objects, infrequent collection
12. What are Extension Methods?
Answer:
Static methods that appear as instance methods of extended type.
csharp
public static class StringExtensions {
public static bool IsNullOrEmpty(this string str) {
return string.IsNullOrEmpty(str);
}
public static string Reverse(this string str) {
return new string(str.Reverse().ToArray());
}
}
// Usage
string text = "hello";
bool isEmpty = text.IsNullOrEmpty(); // Called like instance method
string reversed = text.Reverse();
13. Explain ref and out parameters.
Answer:
-
ref: Pass by reference, variable must be initialized
-
out: Pass by reference, variable doesn't need initialization
csharp
public void ModifyValues(ref int x, out int y) {
x = x * 2; // Can read and modify
y = 100; // Must assign before returning
}
int a = 5;
int b; // Not initialized
ModifyValues(ref a, out b);
// a = 10, b = 100
14. What is the difference between IEnumerable, ICollection, and IList?
Answer:
-
IEnumerable: Basic iteration, read-only forward-only
-
ICollection: Count, Add, Remove, Clear, Contains
-
IList: Index-based access, Insert, RemoveAt
csharp
IEnumerable<int> enumerable = new List<int> { 1, 2, 3 };
// Can only iterate
ICollection<int> collection = new List<int> { 1, 2, 3 };
// Can add, remove, check count
IList<int> list = new List<int> { 1, 2, 3 };
// Can access by index, insert at position
15. What are Attributes in C#?
Answer:
Metadata that adds information to types, methods, properties.
csharp
[Serializable] // Attribute
public class Person {
[Required] // Attribute
[StringLength(50)]
public string Name { get; set; }
[Obsolete("Use NewMethod instead")] // Attribute
public void OldMethod() { }
}
// Custom attribute
[AttributeUsage(AttributeTargets.Class)]
public class AuthorAttribute : Attribute {
public string Name { get; }
public AuthorAttribute(string name) { Name = name; }
}
16. What is Boxing and Unboxing?
Answer:
-
Boxing: Converting value type to object reference
-
Unboxing: Converting object reference back to value type
csharp
int number = 42; // Value type
object boxed = number; // Boxing - value to reference
int unboxed = (int)boxed; // Unboxing - reference to value
// Performance impact - avoid in loops
for (int i = 0; i < 1000000; i++) {
object obj = i; // Boxing - creates new object each time
}
17. What is the difference between Task.Run() and Task.Factory.StartNew()?
Answer:
-
Task.Run: Simplified API, uses default task scheduler, better for CPU-bound work
-
Task.Factory.StartNew: More control over task creation options
csharp
// Preferred for most scenarios
var task1 = Task.Run(() => DoCpuWork());
// More control
var task2 = Task.Factory.StartNew(
() => DoWork(),
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
18. What are Nullable Value Types?
Answer:
Allow value types to represent null values.
csharp
int? nullableInt = null; // Shorthand for Nullable<int>
Nullable<double> nullableDouble = 3.14;
if (nullableInt.HasValue) {
int value = nullableInt.Value; // Access value
}
// Null coalescing operator
int result = nullableInt ?? -1; // Use -1 if null
// Null conditional operator
string name = person?.Name; // Returns null if person is null
19. What is the difference between First() and FirstOrDefault()?
Answer:
-
First(): Throws exception if no elements found
-
FirstOrDefault(): Returns default value if no elements found
csharp
var numbers = new List<int> { 1, 2, 3 };
var first = numbers.First(); // 1
var firstEven = numbers.First(x => x % 2 == 0); // 2
var firstOrDefault = numbers.FirstOrDefault(x => x > 10); // 0 (default int)
// numbers.First(x => x > 10); // Throws InvalidOperationException
20. Explain the SOLID principles.
Answer:
S - Single Responsibility: Class should have one reason to change
O - Open/Closed: Open for extension, closed for modification
L - Liskov Substitution: Derived classes should be substitutable for base classes
I - Interface Segregation: Many specific interfaces better than one general interface
D - Dependency Inversion: Depend on abstractions, not concretions
csharp
// DIP Example
public interface IMessageService {
void Send(string message);
}
public class EmailService : IMessageService {
public void Send(string message) { /* Send email */ }
}
public class Notification {
private readonly IMessageService _messageService;
public Notification(IMessageService messageService) { // Depend on abstraction
_messageService = messageService;
}
public void SendAlert(string message) {
_messageService.Send(message);
}
}
Bonus: Common ASP.NET Core Questions
21. What is Middleware in ASP.NET Core?
Answer:
Software components that handle requests and responses in the pipeline.
csharp
public void Configure(IApplicationBuilder app) {
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
// Custom middleware
public class LoggingMiddleware {
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
// Before logic
Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context); // Call next middleware
// After logic
Console.WriteLine($"Response: {context.Response.StatusCode}");
}
}
22. What is Dependency Injection in ASP.NET Core?
Answer:
Built-in IoC container for managing object lifetimes and dependencies.
csharp
public void ConfigureServices(IServiceCollection services) {
services.AddScoped<IUserService, UserService>(); // Per request
services.AddSingleton<ILogger, FileLogger>(); // Application lifetime
services.AddTransient<IEmailService, EmailService>(); // Every time requested
services.AddControllers();
}
public class UserController : ControllerBase {
private readonly IUserService _userService;
public UserController(IUserService userService) { // Injected by DI container
_userService = userService;
}
}
These questions cover fundamental concepts that are commonly tested in C# and .NET interviews, focusing on both theoretical knowledge and practical implementation.
Comments (0)
No comments yet. Be the first to comment!