C# Interview Mastery

10 Core Concepts • 5 Key Differences • Real Code Examples

#Abstract ClassInterface
1Can have fields & constructorsNo fields or constructors
2Single inheritanceMultiple inheritance
3Can have implemented methodsOnly declarations (C# 8+ default)
4Access modifiers allowedAll public by default
5Share common codeDefine contract
abstract class Animal { public abstract void Speak(); }
interface IDrive { void Drive(); }

class Dog : Animal { public override void Speak() => Console.WriteLine("Woof"); }
class Car : IDrive { public void Drive() => Console.WriteLine("Vroom"); }
#DelegateEvent
1Type-safe function pointerWrapper over delegate
2Can be invoked directlyOnly publisher can raise
3No encapsulationEncapsulated
4Used in LINQ, asyncUsed in GUI, notifications
5Anyone can callOnly class can raise
public delegate void Notify();
public event Notify OnNotify;

Notify handler = () => Console.WriteLine("Called");
handler(); // Direct call

OnNotify += () => Console.WriteLine("Event");
// OnNotify(); // Error
#Static ClassSingleton
1No instanceOne instance
2Cannot inheritCan inherit/implement
3Hard to testEasy to mock
4Loaded at startLazy loading
5No DISupports DI
public static class MathUtils { public static int Add(int a, int b) => a + b; }

public class Logger {
  private static Logger _instance;
  private Logger() {}
  public static Logger Instance => _instance ??= new Logger();
  public void Log(string msg) => Console.WriteLine(msg);
}
#refout
1Must initialize beforeNo init required
2Can read insideCannot read before assign
3Optional assignMust assign
4Modify existingReturn new value
5Two-wayOutput-only
void Modify(ref int x) { x += 10; }
void Get(out int x) { x = 100; }

int a = 5; Modify(ref a); // a = 15
int b; Get(out b); // b = 100
#stringStringBuilder
1ImmutableMutable
2New object on changeSame object
3Slow in loopsFast in loops
4String poolDynamic buffer
5Fixed textDynamic text
string s = "Hi"; s += " there"; // New object

StringBuilder sb = new("Hi");
sb.Append(" there"); // Same object
#BoxingUnboxing
1Value → ObjectObject → Value
2Stack → HeapHeap → Stack
3ImplicitExplicit cast
4Allocates memoryCopies value
5SlowerSlower + exception risk
int i = 10;
object obj = i; // Boxing
int j = (int)obj; // Unboxing
#IEnumerableIQueryable
1In-memoryDatabase-side
2LINQ to ObjectsLINQ to SQL
3Client executionServer execution
4Slower for big dataFaster (SQL)
5List, ArrayDbContext
List list = new() {1,2,3};
var q1 = list.Where(x => x > 1); // IEnumerable

var q2 = db.Users.Where(u => u.Age > 18); // IQueryable
#ThreadTask
1Low-levelHigh-level
2OS managedThreadPool
3HeavyLightweight
4No async/awaitSupports async
5Manual controlAuto managed
new Thread(() => Console.WriteLine("Thread")).Start();

Task.Run(() => Console.WriteLine("Task"));
#constreadonly
1Compile-timeRuntime
2Primitives onlyAny type
3Implicit staticCan be instance
4Never changesSet in constructor
5Substituted in ILStored in memory
public const double Pi = 3.14;
public readonly int Id;
public MyClass(int id) => Id = id;
#==.Equals()
1Reference (default)Value (if overridden)
2Can overloadCan override
3FastSlightly slower
4String: contentString: content
5Null safeRisk of NullRef
string a = "hi", b = "hi";
a == b // True (content)
a.Equals(b) // True

object o1 = new(), o2 = new();
o1 == o2 // False (reference)
o1.Equals(o2) // False

Answer: C# is a modern, object-oriented programming language developed by Microsoft. It runs on the .NET Framework and is designed to be simple, type-safe, and scalable. It combines the power of C/C++ with the ease of Java.

// C# is used to build Windows apps, Web APIs, Games (Unity), etc.
Console.WriteLine("Hello, C#!");

Use Case: Enterprise apps, desktop, web, mobile (Xamarin), cloud (Azure).

Answer: Visual Studio is Microsoft's IDE for developing, debugging, and deploying .NET applications. It supports C#, VB.NET, F#, and more.

Features: Code Editor, Debugger, IntelliSense, Designer, Compiler, Git Integration.

// Write → Build → Run → Debug → Publish — all in one tool

Answer: CLR is the execution engine of .NET. It manages code execution, memory, security, and garbage collection.

Key Roles: JIT Compilation, Exception Handling, Type Safety, GC.

C# → CIL (MSIL) → JIT → Native Machine Code
#Value TypeReference TypePointer Type
1Stores valueStores addressStores memory address
2StackHeapUnsafe context
3Copy on assignReference copyDirect memory access
4int, bool, structclass, string, arrayint*, char*
5Fast, independentShared objectRare, unsafe
int a = 10; int b = a; // Value copy
string s1 = "Hi"; string s2 = s1; // Reference copy
unsafe { int* p = &a; } // Pointer

Categories:

  • Arithmetic: +, -, *, /, %
  • Relational: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !
  • Assignment: =, +=, -=, *=
  • Increment/Decrement: ++, --
  • Bitwise: &, |, ^, ~
  • Ternary: condition ? true : false
  • Null Coalescing: ??
int x = 10;
bool result = (x > 5) ? true : false;
string name = null;
string output = name ?? "Guest";
TypeDescriptionExample
DefaultNo paramspublic Person() {}
ParameterizedTakes inputpublic Person(string n)
CopyCopies objectpublic Person(Person p)
StaticRuns oncestatic Person() {}
PrivateSingletonprivate Person() {}
class Person {
  public Person() {} // Default
  public Person(string n) {} // Param
  static Person() { Console.WriteLine("Static"); }
}

Answer: Destructor (~ClassName) is called by GC to clean up unmanaged resources. Implicitly invoked.

class FileHandler {
  ~FileHandler() {
    Console.WriteLine("File closed");
  }
}

Note: Use IDisposable + Dispose() for deterministic cleanup.

GenerationPurpose
Gen 0Short-lived (temp vars)
Gen 1Medium-lived
Gen 2Long-lived (static, cache)
GC.Collect(); // Force GC (avoid in prod)
GC.SuppressFinalize(this); // After Dispose()

Dispose vs Finalize: Dispose = manual, Finalize = automatic by GC.

PillarDescription
EncapsulationData + Methods in class, hide internals
AbstractionShow essential, hide complex
InheritanceReuse code via parent-child
PolymorphismOne name, many forms
// Polymorphism Example
Animal a = new Dog(); a.Speak(); // "Woof"
#Call by ValueCall by Reference
1Copy passedAddress passed
2No change to originalOriginal modified
3DefaultUse ref / out
void Inc(int x) { x++; } // Value
void IncRef(ref int x) { x++; } // Reference
#Value TypeReference Type
1StackHeap
2Copy on assignReference copy
3struct, intclass, string
#refout
1Must initializeNo init needed
2Can readCannot read before assign
3Optional assignMust assign
#Abstract ClassInterface
1Can have fieldsNo fields
2Single inheritanceMultiple
3ConstructorsNo constructors
#OverloadingOverriding
1Same classParent-child
2Different paramsSame signature
3Compile-timeRuntime
#StackHeap
1Value typesReference types
2Fast, auto-cleanGC managed
3Limited sizeLarge, dynamic
#ManagedUnmanaged
1CLR controlDirect OS
2GCManual free
3C#C++, COM
#DisposeFinalize
1Manual callGC auto
2IDisposable~Class()
3DeterministicNon-deterministic