0% found this document useful (0 votes)
4 views25 pages

Dotnet Notes

The document covers advanced C# concepts including boxing and unboxing, collections and generics, delegates, events, lambda expressions, and LINQ. It explains how generics improve type safety and performance, introduces various collection types like List<T>, Queue<T>, and Stack<T>, and details the use of delegates and events for event-driven programming. Additionally, it discusses LINQ for querying data with deferred and immediate execution concepts, along with advanced language features like indexers and operator overloading.

Uploaded by

s.ramya1292004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views25 pages

Dotnet Notes

The document covers advanced C# concepts including boxing and unboxing, collections and generics, delegates, events, lambda expressions, and LINQ. It explains how generics improve type safety and performance, introduces various collection types like List<T>, Queue<T>, and Stack<T>, and details the use of delegates and events for event-driven programming. Additionally, it discusses LINQ for querying data with deferred and immediate execution concepts, along with advanced language features like indexers and operator overloading.

Uploaded by

s.ramya1292004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C# Advanced Concepts — Complete Study

Notes

UNIT I
1. Boxing and Unboxing
Boxing = converting a value type (int, struct, bool, etc.) into a reference type (object). The
value is copied onto the heap and wrapped inside an object.

Unboxing = converting that boxed object back into a value type. It's an explicit cast, and the
CLR checks the type at runtime.

Why it matters

Value types live on the stack (fast, no GC pressure); reference types live on the heap. Boxing
moves data from stack → heap, which costs performance. Overusing boxing (e.g., putting ints
into a non-generic ArrayList) is a classic performance mistake — this is one of the reasons
Generics were introduced in C# 2.0.

Syntax & Example


int num = 25; // value type on stack

// Boxing (implicit)
object obj = num; // num is copied to heap, wrapped as object

// Unboxing (explicit cast required)


int num2 = (int)obj; // unwraps back to a value type

[Link](num2); // 25

Common pitfall
object obj = 10;
double d = (double)obj; // ❌ InvalidCastException
// must unbox to the EXACT original type first
double d2 = (double)(int)obj; // ✅ correct

Where boxing sneaks in


ArrayList list = new ArrayList();
[Link](5); // boxing: int -> object
int x = (int)list[0]; // unboxing

// Generics avoid this entirely:


List<int> list2 = new List<int>();
[Link](5); // no boxing, type-safe, faster

2. Collections and Generics


2.1 Why Generics?

Generics (List<T>, Dictionary<TKey,TValue>, etc.) let you write type-safe, reusable code
without casting or boxing. T is a placeholder type resolved at compile time.

class Box<T>
{
public T Value;
public void Show() => [Link](Value);
}

Box<int> b1 = new Box<int>();


[Link] = 10;

Box<string> b2 = new Box<string>();


[Link] = "Hello";

2.2 List<T>

A dynamically resizable array. Most commonly used generic collection.

List<int> numbers = new List<int>();


[Link](10);
[Link](20);
[Link](new int[] { 30, 40 });
[Link](10); // removes by value
[Link](0); // removes by index
[Link](1, 99);
bool found = [Link](20);
[Link]();
[Link]();

foreach (int n in numbers)


[Link](n);

Key members: Add, AddRange, Remove, RemoveAt, Insert, Contains, IndexOf, Sort, Count,
Clear.

2.3 Queue<T> — FIFO (First In, First Out)


Queue<string> q = new Queue<string>();
[Link]("A");
[Link]("B");
[Link]("C");

[Link]([Link]()); // A (removes & returns first)


[Link]([Link]()); // B (just looks, doesn't remove)
[Link]([Link]); // 2

Use case: task scheduling, print queues, breadth-first traversal.

2.4 Stack<T> — LIFO (Last In, First Out)


Stack<int> s = new Stack<int>();
[Link](1);
[Link](2);
[Link](3);

[Link]([Link]()); // 3 (removes & returns top)


[Link]([Link]()); // 2 (just looks)
[Link]([Link]); // 2

Use case: undo operations, expression evaluation, recursion simulation, DFS.

2.5 SortedSet<T>

A collection of unique elements, automatically kept in sorted order (uses a self-balancing tree
internally).

SortedSet<int> set = new SortedSet<int>();


[Link](50);
[Link](10);
[Link](30);
[Link](10); // duplicate ignored

foreach (int i in set)


[Link](i); // 10 30 50 (sorted, no duplicates)

[Link]([Link]); // 10
[Link]([Link]); // 50

Use case: whenever you need uniqueness + automatic ordering (e.g., leaderboard of distinct
scores).

Comparison Table

Collection Order Duplicates Access Pattern


List<T> Insertion order Allowed Index-based
Queue<T> FIFO Allowed Enqueue/Dequeue only
Stack<T> LIFO Allowed Push/Pop only
SortedSet<T> Sorted Not allowed Set operations
3. Delegates
A delegate is a type-safe function pointer — an object that holds a reference to a method (or
methods) with a matching signature, and can invoke it.

3.1 Declaring and using a delegate


// 1. Declare delegate type (signature contract)
public delegate int MathOperation(int a, int b);

class Program
{
static int Add(int x, int y) => x + y;
static int Multiply(int x, int y) => x * y;

static void Main()


{
MathOperation op = Add; // assign method
[Link](op(3, 4)); // 7

op = Multiply;
[Link](op(3, 4)); // 12
}
}

3.2 Types of Delegates

1. Singlecast delegate – points to exactly one method (as shown above).


2. Multicast delegate – points to multiple methods; all are invoked in order when the
delegate is called. Built using += / -=.
3. Generic delegates (built-in, avoid custom declarations):
o Action<T...> – returns void
o Func<T..., TResult> – returns a value
o Predicate<T> – returns bool

Action<string> greet = name => [Link]("Hello " + name);


greet("World");

Func<int, int, int> add = (a, b) => a + b;


[Link](add(2, 3)); // 5

Predicate<int> isEven = n => n % 2 == 0;


[Link](isEven(4)); // True

3.3 Multicast Delegates (detail)


public delegate void Notify(string msg);

class Program
{
static void EmailAlert(string msg) => [Link]("Email: " + msg);
static void SmsAlert(string msg) => [Link]("SMS: " + msg);

static void Main()


{
Notify notify = EmailAlert;
notify += SmsAlert; // multicast: now points to 2 methods
notify("Server Down!");
// Output:
// Email: Server Down!
// SMS: Server Down!

notify -= EmailAlert; // remove one


notify("Only SMS now");
}
}

Note: if a multicast delegate has a non-void return type, only the last method's return value is
captured by the caller — the others still execute but their results are discarded.

4. Events
An event is a controlled wrapper around a delegate that follows the publisher/subscriber
pattern. Outside code can only +=/-= to it (subscribe/unsubscribe) — it cannot invoke it directly
or overwrite it with =. This encapsulation is the main difference from a plain delegate.

public delegate void PriceChangedHandler(decimal newPrice);

class Stock
{
public event PriceChangedHandler PriceChanged; // event, based on a
delegate

private decimal price;


public decimal Price
{
get => price;
set
{
price = value;
PriceChanged?.Invoke(price); // raise event (only within class)
}
}
}

class Program
{
static void Main()
{
Stock stock = new Stock();
[Link] += (p) => [Link]($"Price changed to
{p}");
[Link] = 150.50m; // triggers event -> prints "Price changed to
150.50"
}
}

Modern C# typically uses the built-in EventHandler / EventHandler<TEventArgs> delegates:

public class MyEventArgs : EventArgs


{
public string Message { get; set; }
}

class Publisher
{
public event EventHandler<MyEventArgs> Alert;

public void Raise() => Alert?.Invoke(this, new MyEventArgs { Message =


"Alert fired" });
}

5. Lambda Expressions
A lambda expression is a concise, inline anonymous function using => ("goes to").

Syntax
(parameters) => expression_or_statement_block
Func<int, int> square = x => x * x;
[Link](square(5)); // 25

Func<int, int, int> sum = (a, b) => a + b;

Action<string> print = msg => [Link](msg);

// Statement-body lambda (multiple statements need { } and explicit return)


Func<int, int, int> max = (a, b) =>
{
if (a > b) return a;
else return b;
};

Lambdas are heavily used with LINQ:

List<int> nums = new List<int> { 1, 2, 3, 4, 5, 6 };


var evens = [Link](n => n % 2 == 0); // lambda as predicate

6. Anonymous Methods
Introduced in C# 2.0 (before lambdas, C# 3.0), an anonymous method is an unnamed inline
method defined using the delegate keyword.

delegate void Display(string msg);

Display d = delegate (string msg)


{
[Link]("Message: " + msg);
};
d("Hello Anonymous Method");

Anonymous method vs lambda: Lambdas are the modern, shorter syntax and are generally
preferred; anonymous methods are functionally similar but more verbose and can't use
expression-bodied syntax.

// Anonymous method
Func<int, int, int> add1 = delegate (int a, int b) { return a + b; };

// Equivalent lambda
Func<int, int, int> add2 = (a, b) => a + b;

7. Advanced C# Language Features


7.1 Indexer

An indexer lets an object be accessed like an array using [], defined with the this keyword.

class Week
{
private string[] days = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };

// Indexer
public string this[int index]
{
get => days[index];
set => days[index] = value;
}
}

Week w = new Week();


[Link](w[1]); // Mon
w[1] = "Monday";
[Link](w[1]); // Monday

Indexers can also be overloaded (e.g., accept a string key instead of int), similar to a
dictionary-style lookup.

7.2 Operator Overloading


C# allows redefining how built-in operators (+, -, ==, etc.) behave for custom types.

Binary operator overloading (needs two operands):

class Complex
{
public int Real, Imaginary;
public Complex(int r, int i) { Real = r; Imaginary = i; }

public static Complex operator +(Complex a, Complex b)


=> new Complex([Link] + [Link], [Link] + [Link]);

public override string ToString() => $"{Real} + {Imaginary}i";


}

Complex c1 = new Complex(2, 3);


Complex c2 = new Complex(4, 5);
Complex c3 = c1 + c2; // uses overloaded +
[Link](c3); // 6 + 8i

Unary operator overloading (needs one operand):

class Counter
{
public int Value;
public Counter(int v) { Value = v; }

public static Counter operator ++(Counter c) => new Counter([Link] + 1);


public static Counter operator -(Counter c) => new Counter(-[Link]);
}

Counter c = new Counter(5);


c++; // uses overloaded unary ++
[Link]([Link]); // 6

Overloadable operators include: + - * / % ++ -- ! ~ true false == != < > <= >=


(comparison operators must be overloaded in pairs).

7.3 Equality and Comparison

To make custom types comparable / usable correctly in collections (SortedSet<T>,


List<T>.Sort, dictionaries), you implement standard interfaces instead of only overloading
operators.

IEquatable<T> — defines value equality:

class Point : IEquatable<Point>


{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }

public bool Equals(Point other)


=> other != null && X == other.X && Y == other.Y;

public override bool Equals(object obj) => Equals(obj as Point);


public override int GetHashCode() => [Link](X, Y);

public static bool operator ==(Point a, Point b) => [Link](b);


public static bool operator !=(Point a, Point b) => ![Link](b);
}

IComparable<T> — defines ordering (required for Sort(), SortedSet<T>):

class Employee : IComparable<Employee>


{
public string Name;
public int Salary;

public int CompareTo(Employee other) => [Link]([Link]);


}

List<Employee> emps = new List<Employee> { /* ... */ };


[Link](); // sorts by Salary ascending, using CompareTo

IComparer<T> — an external/alternate comparison strategy (useful when you need multiple sort
orders without changing the class itself):

class ByNameComparer : IComparer<Employee>


{
public int Compare(Employee a, Employee b) => [Link]([Link],
[Link]);
}

[Link](new ByNameComparer());
Interface Purpose Method
IEquatable<T> value equality bool Equals(T other)
IComparable<T> natural ordering int CompareTo(T other)
IComparer<T> external/custom ordering int Compare(T a, T b)

UNIT II — LINQ
1. What is LINQ?
LINQ (Language Integrated Query) is a set of C# language and library features that let you
write SQL-like queries directly in C# to query collections, databases, XML, and more — with
compile-time type checking and IntelliSense support.

Types of LINQ
Type Queries
LINQ to Objects In-memory collections (List<T>, arrays, etc.)
LINQ to SQL SQL Server database tables (legacy ORM)
LINQ to Entities Entity Framework / EF Core data models
LINQ to XML XML documents (XElement, XDocument)
LINQ to DataSet [Link] DataSet/DataTable objects
Parallel LINQ (PLINQ) Parallelized queries over collections

2. LINQ to Objects — Query Syntax vs Method Syntax


int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Query syntax (SQL-like)


var evenQ = from n in numbers
where n % 2 == 0
orderby n descending
select n;

// Method syntax (fluent, lambda-based) — equivalent


var evenM = [Link](n => n % 2 == 0)
.OrderByDescending(n => n);

foreach (int n in evenQ)


[Link](n);

Common LINQ operators


[Link](n => n * n); // projection
[Link](n => n > 5); // filtering
[Link](n => n); // sorting ascending
[Link](n => n);
[Link](); [Link]();
[Link](); [Link](); [Link](); [Link]();
[Link]();
[Link](n => n > 100); // does any match?
[Link](n => n > 0); // do all match?
[Link](3); [Link](3);
[Link](n => n % 2); // grouping
[Link]();

3. Deferred Execution vs Immediate Execution


This is a critical LINQ concept.

Deferred Execution

The query is not run when it's defined — it's run only when you actually iterate over it
(foreach, .ToList(), etc.). Operators like Where, Select, OrderBy are deferred.
List<int> nums = new List<int> { 1, 2, 3 };

var query = [Link](n => n > 1); // NOT executed yet — just builds the
query

[Link](4); // modify source AFTER defining query

foreach (int n in query)


[Link](n); // executes NOW -> prints 2, 3, 4 (includes the new
item!)

Immediate Execution

Operators that return a single value or a materialized collection — like Count(), ToList(),
ToArray(), First(), Sum(), Max() — force the query to run right away.

List<int> nums = new List<int> { 1, 2, 3 };

var result = [Link](n => n > 1).ToList(); // executes IMMEDIATELY

[Link](4); // this change has NO effect on 'result'

foreach (int n in result)


[Link](n); // prints only 2, 3
Deferred Immediate
On iteration (foreach,
Trigger On the call itself
enumeration)
Reflects later source
Yes No (snapshot)
changes
Where, Select, OrderBy, query ToList(), ToArray(), Count(),
Examples
syntax Sum(), First()

4. Understanding Object Lifetime — Garbage Collection


(GC)
.NET uses automatic memory management. The Garbage Collector (GC) periodically
reclaims heap memory occupied by objects that are no longer reachable/referenced by the
application, so developers don't manually free() memory.

How it works (basics)

 Objects are allocated on the managed heap.


 The GC traces object graphs from roots (static fields, local variables, CPU registers) to
determine which objects are still reachable.
 Unreachable objects are considered garbage and their memory is reclaimed.

Generations of Garbage Collection


The GC uses a generational model — based on the observation that most objects die young —
to optimize performance by not scanning the entire heap every time.

Generation Contains Collected


Gen 0 Newly created, short-lived objects Very frequently (fast, cheap)
Objects that survived a Gen 0 collection; buffer
Gen 1 Occasionally
zone
Long-lived objects (e.g., static data, caches) that Rarely (most expensive, scans more
Gen 2
survived Gen 1 memory)
// Conceptual flow:
// object created -> placed in Gen 0
// Gen 0 fills up -> GC runs on Gen 0
// survivors promoted -> Gen 1
// Gen 1 fills up -> GC runs on Gen 1
// survivors promoted -> Gen 2
// Gen 2 objects are collected only in a "full GC"

There is also a special Large Object Heap (LOH) for objects ≥ 85,000 bytes, collected along
with Gen 2.

Finalizable and Disposable Objects

Some objects hold unmanaged resources (file handles, database connections, network sockets,
GDI handles) that the GC doesn't know how to clean up directly. Two mechanisms exist:

1. Finalizers (destructors) — a safety net, called by the GC before reclaiming an object, but
timing is non-deterministic and it slows down collection.

class ResourceHolder
{
~ResourceHolder() // finalizer / destructor syntax
{
// cleanup unmanaged resources
[Link]("Finalizer called");
}
}

2. IDisposable / Dispose() — the preferred, deterministic cleanup pattern. The consumer


explicitly calls Dispose() (often via using) as soon as the resource is no longer needed.

class FileHandler : IDisposable


{
private FileStream stream = new FileStream("[Link]",
[Link]);

public void Dispose()


{
[Link](); // release unmanaged resource immediately
[Link](this); // tell GC no need to finalize (already
cleaned up)
[Link]("Disposed");
}
}

// Usage
using (FileHandler fh = new FileHandler())
{
// use fh
} // Dispose() called automatically here, even if an exception occurs

// Modern C# 8+ shorthand
using FileHandler fh2 = new FileHandler();

Best practice — Dispose pattern combining both:

class Resource : IDisposable


{
private bool disposed = false;

protected virtual void Dispose(bool disposing)


{
if (!disposed)
{
if (disposing) { /* dispose managed resources */ }
/* free unmanaged resources */
disposed = true;
}
}

public void Dispose()


{
Dispose(true);
[Link](this);
}

~Resource() => Dispose(false); // fallback finalizer


}

5. Building and Configuring Class Libraries — Role of .NET


Assemblies
A Class Library is a compiled, reusable unit of code (.dll) — as opposed to an executable
(.exe) — containing classes, interfaces, and resources that other projects can reference.

Creating a class library (CLI)


dotnet new classlib -n MyMathLibrary
cd MyMathLibrary
dotnet build # produces [Link]
// MyMathLibrary/[Link]
namespace MyMathLibrary
{
public class Calculator
{
public int Add(int a, int b) => a + b;
}
}

Reference it from another project:

dotnet add reference ../MyMathLibrary/[Link]


using MyMathLibrary;
var calc = new Calculator();
[Link]([Link](2, 3));

What is an Assembly?

An assembly is the fundamental unit of deployment, versioning, and security in .NET — a


compiled .dll or .exe file that is self-describing via metadata.

Role of assemblies:

1. Unit of deployment — the compiled package you ship (DLL/EXE).


2. Contains IL (Intermediate Language) code — compiled from C#, executed by the
CLR (JIT-compiled to native code at runtime).
3. Contains Metadata — describes types, members, and references within the assembly
(used for reflection, IntelliSense).
4. Contains a Manifest — assembly-level metadata: name, version, culture, strong name
(public key), and a list of referenced assemblies.
5. Unit of versioning — each assembly has a version number ([Link]), enabling side-by-
side versioning.
6. Security boundary — permissions can be scoped at the assembly level.
7. Types:
o Private assembly — used only by one application, deployed in the app's folder.
o Shared assembly — placed in the Global Assembly Cache (GAC) (legacy .NET
Framework), usable by multiple applications, requires a strong name.
o Satellite assembly — contains localized resources only (for globalization).

// Inspecting assembly info via reflection


using [Link];

Assembly asm = [Link]();


[Link]([Link]);
[Link]([Link]().Version);

6. Understanding Late Binding


Early binding (normal C# code): the compiler resolves which method/type to call at compile
time — fast, type-safe.

Late binding: the type/method is resolved at runtime, not compile time. Used when the exact
type isn't known until the program runs (e.g., loading plugins dynamically, COM interop,
reflection-based frameworks).

Late binding via Reflection


using [Link];

// Load an assembly dynamically at runtime


Assembly asm = [Link]("[Link]");

// Get the type by name (not known at compile time)


Type calcType = [Link]("[Link]");

// Create an instance dynamically


object calcInstance = [Link](calcType);

// Invoke a method dynamically


MethodInfo addMethod = [Link]("Add");
object result = [Link](calcInstance, new object[] { 5, 10 });

[Link](result); // 15

Late binding via dynamic keyword (C# 4+)


dynamic obj = GetSomeObject(); // type resolved at runtime
[Link](); // compiler doesn't check this until runtime
Early Binding Late Binding
Resolved Compile time Runtime
Speed Faster Slower (reflection overhead)
Type safety Compile-time checked Runtime errors possible
Use case Normal application code Plugins, COM interop, reflection frameworks

7. Introducing LINQ to XML


LINQ to XML is an in-memory XML programming API that lets you create, query, and modify
XML documents using LINQ syntax — far simpler than the older XmlDocument/DOM API. The
main namespace is [Link].

Core classes

 XElement — represents a single XML element (the most commonly used class).
 XDocument — represents an entire XML document (optionally including a declaration,
comments, processing instructions).
 XAttribute — represents an attribute of an element.

Creating XML with XElement


using [Link];

XElement student = new XElement("Student",


new XAttribute("RollNo", "101"),
new XElement("Name", "Arjun"),
new XElement("Marks", "95")
);

[Link](student);
/* Output:
<Student RollNo="101">
<Name>Arjun</Name>
<Marks>95</Marks>
</Student>
*/

Creating a full document with XDocument


XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Students",
new XElement("Student",
new XAttribute("RollNo", "101"),
new XElement("Name", "Arjun"),
new XElement("Marks", 95)
),
new XElement("Student",
new XAttribute("RollNo", "102"),
new XElement("Name", "Divya"),
new XElement("Marks", 88)
)
)
);

[Link]("[Link]");
[Link](doc);

Loading and Querying XML with LINQ


XDocument doc = [Link]("[Link]");

// Query using LINQ syntax


var names = from s in [Link]("Student")
where (int)[Link]("Marks") > 90
select [Link]("Name").Value;

foreach (var n in names)


[Link](n); // Arjun

// Method syntax equivalent


var names2 = [Link]("Student")
.Where(s => (int)[Link]("Marks") > 90)
.Select(s => [Link]("Name").Value);

Modifying XML
XElement el = [Link]("Student").First();
[Link]("Marks").Value = "99"; // update
[Link](new XElement("Grade", "A")); // add new child
[Link]("RollNo").Remove(); // remove attribute
[Link]("students_updated.xml");

Key members quick reference

Member Purpose
[Link]() direct child elements
[Link]() all nested elements (recursive)
[Link]("name") get an attribute
[Link] text content
[Link](path) parse XML from a file/stream
[Link](string) parse XML from a string
[Link](path) write XML to a file

Quick Summary Map

value type ⇄ object, heap copy, avoid with generics


Topic Key idea
Boxing/Unboxing
List/Queue/Stack/SortedSet generic type-safe collections, each with a distinct access pattern
Delegates type-safe method references; single or multicast
Events encapsulated, restricted delegates (publisher/subscriber)
Lambda / Anonymous methods inline unnamed functions, lambdas are the modern shorthand
Indexer array-like [] access on custom objects
Operator overloading redefine +, -, ==, unary/binary operators for custom types
Equality/Comparison IEquatable<T>, IComparable<T>, IComparer<T>
LINQ unified query syntax over objects, XML, SQL, EF, DataSets
Deferred vs Immediate query built vs query executed
GC & Generations automatic memory reclamation, Gen 0/1/2 optimization
IDisposable / Finalizers deterministic vs GC-driven cleanup of unmanaged resources
Assemblies compiled, versioned, self-describing deployment unit
Late Binding runtime type/method resolution via reflection or dynamic
LINQ to XML XElement/XDocument for querying & building XML
C# & LINQ — All Differentiations /
Comparison Tables

UNIT I
1. Value Type vs Reference Type

Basis Value Type Reference Type


Storage Stack (usually) Heap
Contains Actual data Reference/address to data
Examples int, float, struct, enum, bool class, string, array, object, interface
Copy behavior Copies the value Copies the reference (both point to same object)
Default value 0/false/etc. null
Performance Faster, no GC overhead Slower, managed by GC

2. Boxing vs Unboxing

Basis Boxing Unboxing


Direction Value type → object (reference type) object → Value type
Conversion Implicit Explicit (needs cast)
Memory Stack → Heap (allocates new memory) Heap → Stack (copies out value)
Example object o = 10; int i = (int)o;
Risk Minimal InvalidCastException if wrong type cast

3. Generic Collections vs Non-Generic Collections

Basis Generic (List<T>, Dictionary<K,V>) Non-Generic (ArrayList, Hashtable)


Type safety Compile-time type checked Not type-safe (stores as object)
Boxing/unboxing Not needed for value types Required for value types → slower
Performance Faster Slower
Namespace [Link] [Link]
Casting needed No Yes, when retrieving items

4. List<T> vs Array

Basis List<T> Array


Size Dynamic (resizes automatically) Fixed at creation
Namespace [Link] System
Methods Rich (Add, Remove, Sort, etc.) Very limited built-in methods
Basis List<T> Array
Performance Slight overhead due to resizing Slightly faster (fixed, no resize)
Memory May over-allocate for growth Exact size allocated

5. Queue<T> vs Stack<T>

Basis Queue<T> Stack<T>


Order FIFO (First In, First Out) LIFO (Last In, First Out)
Insert method Enqueue() Push()
Remove method Dequeue() Pop()
Peek Views front element Views top element
Use case Task scheduling, BFS Undo operations, DFS, expression evaluation

6. List<T> vs SortedSet<T>

Basis List<T> SortedSet<T>


Order Insertion order Always sorted
Duplicates Allowed Not allowed (unique elements only)
Access By index No direct index access
Underlying structure Dynamic array Self-balancing binary tree
Use case General-purpose ordered list Unique + sorted data (e.g., leaderboard)

7. Delegate vs Event

Basis Delegate Event


Definition Type-safe function pointer Wrapper around a delegate
Can be invoked/called from anywhere Can only be raised (Invoke) from within
Invocation
it's accessible the declaring class
Assignment Can be overwritten with = from outside Cannot use = from outside; only += / -=
General-purpose method Specifically for publisher–subscriber
Purpose
reference/callback notification pattern
Encapsulation Less restricted More encapsulated / safer

8. Singlecast Delegate vs Multicast Delegate

Basis Singlecast Multicast


Methods referenced Exactly one Multiple (invocation list)
Combine with = (assignment) += (add), -= (remove)
Return value (non- The single method's return Only the last invoked method's return value is
void) value returned to caller
Example op = Add; notify = M1; notify += M2;

9. Lambda Expression vs Anonymous Method


Basis Lambda Expression Anonymous Method
(params) =>
Syntax expression/block
delegate(params) { ... }

Introduced in C# 3.0 C# 2.0


Conciseness Shorter, more readable More verbose
No, must specify explicitly if
Can omit parameters Yes (in some overloads)
used
Compiles to expression
Yes (for Expression<T>) No
trees
Modern usage Preferred / widely used Largely legacy, rarely used now

10. Func<T> vs Action<T> vs Predicate<T>

Basis Func<T> Action<T> Predicate<T>


Return type Returns a value (last type param) Returns void Always returns bool
Parameters 0 to 16 input params 0 to 16 input params Exactly 1 input param
Example Func<int,int,int> add Action<string> print Predicate<int> isEven
Typical use Calculations, transformations Side-effect operations Conditions/filters

11. Indexer vs Property

Basis Indexer Property


Access syntax obj[index] [Link]
Declared with this[...] keyword Property name
Parameters Accepts parameters (index) No parameters
Purpose Array-like access to object data Access to a single field/value
Overloading Can be overloaded (multiple indexers) Cannot be overloaded

12. Method Overloading vs Operator Overloading

Basis Method Overloading Operator Overloading


What's Multiple methods, same name,
Behavior of an existing operator (+, -, ==)
redefined different signatures
Keyword Normal method declaration operator keyword
Provide multiple ways to call a Make operators work meaningfully on
Purpose
method custom types
public static Complex operator +
Example Add(int,int), Add(double,double) (Complex a, Complex b)

13. Unary vs Binary Operator Overloading

Basis Unary Operator Overloading Binary Operator Overloading


Operands One Two
Examples ++, --, unary -, ! +, -, *, /, ==, !=
Basis Unary Operator Overloading Binary Operator Overloading
Method signature operator ++(Type a) operator +(Type a, Type b)

14. IEquatable<T> vs IComparable<T> vs IComparer<T>

Basis IEquatable<T> IComparable<T> IComparer<T>


Natural/default
Purpose Value equality check External/custom ordering
ordering
bool Equals(T int CompareTo(T
Method other) other)
int Compare(T x, T y)

Implemented
The class itself The class itself A separate helper class
on
.Equals(), collections
, List<T>.Sort(IComparer<T>)
Used by needing equality (e.g. List<T>.Sort()
SortedSet<T> when multiple sort orders needed
HashSet<T>)

15. == Operator vs .Equals() Method

Basis == .Equals()
Default behavior (reference Reference comparison (unless
Reference comparison
types) overridden)
Default behavior (value
Value comparison Value comparison
types)
Overridable Yes (via operator ==) Yes (via override Equals)
Compares content (special-
string behavior Compares content
cased)
Resolved at compile time Can be overridden, resolved via
Polymorphism
(static binding) virtual dispatch

UNIT II — LINQ
16. LINQ Query Syntax vs Method Syntax

Basis Query Syntax Method Syntax


SQL-like
Style Fluent, chained methods with lambdas
(from...where...select)
Readability Easier for SQL-familiar devs More flexible, closer to underlying API
Compiles to Method syntax internally Direct extension method calls
Some operators only Method syntax (e.g. Count(),

available in FirstOrDefault(), Take())
from n in nums where n>5
Example select n
[Link](n => n > 5)
17. Types of LINQ — Comparison

Type Data Source


LINQ to Objects In-memory collections (arrays, List<T>, etc.)
LINQ to SQL SQL Server tables (legacy, direct mapping)
LINQ to Entities Entity Framework data models (any supported DB)
LINQ to XML XML documents (XElement/XDocument)
LINQ to DataSet [Link] DataSet/DataTable
PLINQ Same as LINQ to Objects, but parallelized across cores

18. Deferred Execution vs Immediate Execution

Basis Deferred Execution Immediate Execution


Only when enumerated (foreach, Immediately when the statement
When query runs
iteration) is called
Reflects later
Yes No (result is a fixed snapshot)
changes to source
Where, Select, OrderBy, query-syntax ToList(), ToArray(), Count(),
Typical operators
expressions Sum(), First(), Max()
Performance Query re-runs every enumeration (can be Runs once, result cached in
implication costly if enumerated multiple times) memory

19. First() vs FirstOrDefault() vs Single()

Basis First() FirstOrDefault() Single()


Empty Returns default value (e.g.
Throws exception Throws exception
sequence 0/null)
Multiple Throws exception (must be
Returns first match Returns first match
matches exactly one match)
Expect at least one, Expect exactly one unique
Use case Safe lookup, may not exist
only need first match

20. Garbage Collection Generations (Gen 0 vs Gen 1 vs Gen 2)

Basis Gen 0 Gen 1 Gen 2


Newly created, short- Objects that survived one Long-lived objects that
Contains
lived objects Gen 0 collection survived Gen 1
Collection
Very frequent Occasional Rare
frequency
Most expensive (full
Collection cost Cheapest/fastest Moderate
scan)
Example Temporary local Static data, caches,
Medium-lifetime objects
objects variables singletons
21. Finalize() (Destructor) vs Dispose()

Finalize() / Destructor
Basis Dispose() (IDisposable)
(~ClassName())
Explicitly by the developer (or
Called by Garbage Collector automatically
using statement)
Deterministic (immediate, as soon
Timing Non-deterministic (whenever GC runs)
as called)
Slower — object needs an extra GC Faster — resource released
Performance
cycle to be collected immediately
Safety-net cleanup of unmanaged Primary/preferred cleanup
Typical use
resources mechanism
Can be called
No Yes
manually

22. Managed Resources vs Unmanaged Resources

Basis Managed Resources Unmanaged Resources


Cleaned up .NET Garbage Collector Must be released manually (via
by automatically Dispose/Finalize)
File handles, DB connections, sockets, GDI
Examples Objects, arrays, most .NET types
objects

23. Early Binding vs Late Binding

Basis Early Binding Late Binding


Resolved at Compile time Runtime
Type Compile-time
Runtime (errors surface only when executed)
checking (safe)
Performance Faster Slower (reflection/dynamic dispatch overhead)
Normal method Reflection ([Link],
Mechanism
calls [Link]), dynamic keyword
Standard
Use case Plugin systems, COM interop, dynamically loaded assemblies
application code

24. Private Assembly vs Shared Assembly

Basis Private Assembly Shared Assembly


Used by a single application
Usage scope Can be used by multiple applications
only
Application's own folder Global Assembly Cache (GAC) — legacy .NET
Location
(bin) Framework
Strong name
No Yes
required
Basis Private Assembly Shared Assembly
Versioning Simpler Supports side-by-side versioning

25. Assembly vs Namespace

Basis Assembly Namespace


Logical grouping/organization of types in
What it is Physical compiled unit (.dll/.exe)
code
Not a deployable unit, purely
Deployment Deployed as a file
organizational
One assembly can contain multiple One namespace can span multiple
Can span
namespaces assemblies
Contains IL code, metadata, manifest Classes, interfaces, structs, etc.

26. XElement vs XDocument (LINQ to XML)

Basis XElement XDocument


A single XML element (and its
Represents An entire XML document
children)
Declaration, comments, processing
Contains Just element data
instructions, root element
Root Can exist standalone (no need for a
Typically has one root XElement
requirement full document)
Building/reading individual elements
Common use Loading/saving complete XML files
quickly

27. LINQ to XML vs Traditional XmlDocument (DOM)

Basis LINQ to XML (XElement/XDocument) XmlDocument (traditional DOM)


Imperative, node-by-node
API style Functional construction + LINQ queries
manipulation
Code
Concise, declarative Verbose
readability
Query Full LINQ query support (Where, Select,
Requires XPath or manual traversal
capability etc.)
Introduced in .NET 3.5 ([Link]) Since .NET 1.0 ([Link])

28. Class Library vs Console/Executable Application

Basis Class Library (.dll) Console/Executable Application (.exe)


Output DLL (not directly runnable) EXE (directly runnable, has entry point)
Entry point No Main() method Has a Main() method
Purpose Reusable code shared across projects Standalone runnable program
Basis Class Library (.dll) Console/Executable Application (.exe)
Usage Referenced by other projects Run directly by the OS/CLR

Quick Master Table (topic → what differentiates it)


# Differentiation Core distinguishing factor
1 Value vs Reference type Where data is stored
2 Boxing vs Unboxing Direction of value↔object conversion
3 Generic vs Non-generic collections Type safety & performance
4 List<T> vs Array Fixed vs dynamic size
5 Queue<T> vs Stack<T> FIFO vs LIFO
6 List<T> vs SortedSet<T> Order & duplicates
7 Delegate vs Event Encapsulation of invocation
8 Singlecast vs Multicast delegate Number of methods referenced
9 Lambda vs Anonymous method Syntax conciseness & era
10 Func vs Action vs Predicate Return type shape
11 Indexer vs Property Parameterized [] access vs simple access
12 Method vs Operator overloading What is being redefined
13 Unary vs Binary operator overloading Number of operands
14 IEquatable vs IComparable vs IComparer Equality vs internal order vs external order
15 == vs Equals() Static vs virtual dispatch
16 Query vs Method syntax SQL-like vs fluent chaining
17 Types of LINQ Underlying data source
18 Deferred vs Immediate execution When the query actually runs
19 First vs FirstOrDefault vs Single Behavior on empty/multiple results
20 Gen 0 vs Gen 1 vs Gen 2 (GC) Object lifetime & collection frequency
21 Finalize() vs Dispose() Automatic vs deterministic cleanup
22 Managed vs Unmanaged resources Who cleans it up
23 Early vs Late binding Compile-time vs runtime resolution
24 Private vs Shared assembly Single-app vs multi-app usage
25 Assembly vs Namespace Physical file vs logical grouping
26 XElement vs XDocument Single element vs whole document
27 LINQ to XML vs XmlDocument Declarative vs imperative XML API
28 Class Library vs Executable DLL (referenced) vs EXE (runnable)

You might also like