- Value Types: Store data directly (e.g., int, struct), allocated on the stack, copied by value. - Reference Types: Store a reference to data (e.g., class, string), allocated on the heap, copied by reference. - Comparison: Value types are faster for small data but immutable; reference types support complex objects but involve garbage collection. Example:
int a = 10; // Value type
string b = "Hello"; // Reference type
int c = a; // Copy value
string d = b; // Copy reference
C#Exception HandlingError Management
Exception handling in C# uses `try`, `catch`, `finally`, and `throw` to handle runtime errors gracefully. Example:
try {
int x = 0;
int y = 10 / x;
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: " + ex.Message);
} finally {
Console.WriteLine("Cleanup");
}
C#Property AccessorsEncapsulation
Property accessors in C# are the `get` and `set` methods used to read and write a property's value, providing controlled access to a private field. Example:
class Person {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
}
C#Language Overview
C# is a modern, object-oriented programming language developed by Microsoft, used for building applications on the .NET framework, known for its type safety and versatility.
C#Continue StatementBreak StatementControl Flow
- break: Exits the loop immediately. - continue: Skips the current iteration and proceeds to the next. Example:
for (int i = 0; i < 5; i++) {
if (i == 2) continue; // Skips 2
if (i == 4) break; // Exits at 4
Console.WriteLine(i);
} // Outputs: 0, 1, 3
C#ObjectOOP
An object is an instance of a class, containing data and behavior defined by the class, created at runtime. Example:
class Dog {
public string Name { get; set; }
}
Dog dog = new Dog { Name = "Rex" }; // Object
C#SerializationData Persistence
Serialization is the process of converting an object into a stream of bytes for storage or transmission, and deserialization is the reverse. Example:
[Serializable]
class Person {
public string Name { get; set; }
}
C#Partial ClassesCode Organization
Partial classes allow a class definition to be split across multiple files, useful for code organization and auto-generated code. Example:
partial class MyClass {
public void Method1() { }
}
partial class MyClass {
public void Method2() { }
}
C#GenericsType Safety
Generics allow defining classes, methods, or interfaces with a placeholder type, enabling type-safe, reusable code without casting. Example:
class GenericList {
public void Add(T item) { }
}
GenericList list = new GenericList();
C#This KeywordStatic Methods
No, `this` cannot be used in a static method because it refers to the current instance, and static methods are not tied to instances. Example:
No, only the first matching `catch` block is executed for a given exception. Example:
try {
throw new Exception();
} catch (ArgumentException) {
// Not executed
} catch (Exception) {
// Executed
}
C#Finally BlockException Handling
The `finally` block executes regardless of whether an exception occurs, ensuring cleanup tasks like closing resources are performed. Example:
try {
// Code that may throw exception
} catch {
// Handle exception
} finally {
Console.WriteLine("Always executed");
}
C#Class TypesOOP
- Concrete: Instantiable classes. - Abstract: Cannot be instantiated, used as base classes. - Sealed: Cannot be inherited. - Static: Contains only static members. - Partial: Split across multiple files. Example:
abstract class A { }
sealed class B { }
static class C { }
partial class D { }
C#Managed CodeUnmanaged Code.NET
- Managed Code: Runs under CLR, with memory management (e.g., C#). - Unmanaged Code: Runs outside CLR, no automatic memory management (e.g., C++).
C#StringStringBuilderPerformance
- string: Immutable, each modification creates a new object. - StringBuilder: Mutable, efficient for frequent modifications. Example:
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append("World");
C#Reference TypesData Types
Reference types store a reference to data on the heap (e.g., classes, interfaces, arrays, strings). Example:
string s = "Hello"; // Reference type
object o = new object();
C#LINQQuerying
LINQ (Language Integrated Query) is a set of extensions for querying data in C#, supporting collections, databases, XML, etc. Example:
int[] numbers = { 1, 2, 3, 4 };
var even = from n in numbers where n % 2 == 0 select n;
C#ClassStructComparison
- Class: Reference type, heap-allocated, supports inheritance. - Structure: Value type, stack-allocated, no inheritance. Example:
class MyClass { public int X; }
struct MyStruct { public int X; }
C#BoxingUnboxingPerformance
- Boxing: Converting a value type to a reference type (object). - Unboxing: Converting a reference type back to a value type. Example:
int i = 123;
object o = i; // Boxing
int j = (int)o; // Unboxing
C#StructClassComparison
Same as Q19: Class is reference type, struct is value type; classes support inheritance, structs do not. Example:
class C { public int X; }
struct S { public int X; }
C#Abstract ClassOOP
An abstract class cannot be instantiated and may contain abstract methods (no implementation) and concrete methods, used as a base class. Example:
abstract class Shape {
public abstract void Draw();
}
C#NamespaceCode Organization
A namespace organizes code into logical groups to avoid naming conflicts and improve readability. Example:
namespace MyApp {
class MyClass { }
}
C#Method ParametersParameter Passing
- Value: Copy of the value. - Reference (ref): Reference to the variable. - Output (out): For returning values. - Params: Variable number of arguments. Example:
void Method(int a, ref int b, out int c, params int[] d) {
c = 0;
}
C#Nullable TypesNull Handling
Nullable types allow value types to represent `null`, using the `?` operator or `Nullable`. Example:
int? x = null;
Nullable y = null;
C#EnumData Types
An enum is a value type defining a set of named constants, typically used for fixed values. Example:
enum Days { Monday, Tuesday, Wednesday }
C#Exception HandlingMultiple Exceptions
Yes, use a single `catch` block with a base exception type or C# 6.0+ exception filters to handle multiple exceptions. Example:
try {
// Code
} catch (Exception ex) when (ex is ArgumentNullException || ex is InvalidOperationException) {
// Handle
}
C#RecordAssignmentCopying
- Assignment: Copies the reference (same object). - Shallow Copy: Copies top-level fields, references remain shared. - Deep Copy: Copies all fields and nested objects. Example:
record Person(string Name);
Person p1 = new Person("Alice");
Person p2 = p1; // Assignment
Person p3 = p1 with { }; // Deep copy
C#Dynamic TypesType Safety
Dynamic type variables (`dynamic`) bypass compile-time type checking, resolved at runtime. Example:
dynamic x = 10;
x = "Hello";
C#RecordClassStruct
- Record: For immutable data with value semantics. - Class: For complex objects with reference semantics. - Struct: For small, immutable data with value semantics. Example:
record R(string Name);
class C { public string Name; }
struct S { public string Name; }
C#InterfaceAccessibility
Interface methods are implicitly `public` to ensure consistent contract implementation across classes. Example:
interface IExample {
void Method(); // Implicitly public
}
C#RecordImmutability
A record is a reference type with value-based equality, immutability by default, and concise syntax for data objects. Example:
record Person(string Name, int Age);
C#Anonymous FunctionDelegates
An anonymous function is a method without a name, typically defined using delegates or lambda expressions. Example:
A virtual method can be overridden in a derived class, enabling polymorphism. Example:
class Base {
public virtual void Method() { }
}
class Derived : Base {
public override void Method() { }
}
C#Using StatementResource Management
- Namespace Import: Access types without full qualification. - Resource Management: Ensures `IDisposable` objects are disposed. Example:
using System;
using (var stream = new FileStream("file.txt", FileMode.Open)) { }
C#Virtual MethodAbstract Method
- Virtual: Has default implementation, optional override. - Abstract: No implementation, must be overridden. Example:
abstract class Base {
public virtual void V() { }
public abstract void A();
}
class Derived : Base {
public override void A() { }
}
C#Extension MethodsCode Reusability
Extension methods add functionality to existing types using static methods in a static class. Example:
static class StringExtensions {
public static string Reverse(this string s) => new string(s.Reverse().ToArray());
}
string s = "Hello".Reverse();
C#Ref KeywordOut KeywordParameters
- ref: Parameter must be initialized before passing, can be read/write. - out: Must be assigned in method, cannot be read before assignment. Example:
void Method(ref int a, out int b) {
a = a + 1;
b = 10;
}
C#Pointer TypesUnsafe Code
Pointer types in C# (`*`) allow direct memory access in `unsafe` contexts, used for performance-critical code. Example:
unsafe {
int x = 10;
int* p = &x;
}
C#Internal ModifierAccess Control
An `internal` member is accessible only within the same assembly. Example:
internal class MyClass {
internal int X;
}
C#Variable ArgumentsMethod Parameters
Yes, use the `params` keyword to accept a variable number of arguments. Example:
void Sum(params int[] numbers) {
int total = numbers.Sum();
}
Sum(1, 2, 3);
C#IndexerProperties
Indexers allow objects to be indexed like arrays using `this` keyword. Example:
class MyCollection {
private int[] data = new int[10];
public int this[int i] {
get => data[i];
set => data[i] = value;
}
}
C#DisposeFinalizeResource Management
- Dispose: Deterministic cleanup via `IDisposable`. - Finalize: Non-deterministic cleanup via destructor, called by GC. Example:
class Resource : IDisposable {
public void Dispose() { }
~Resource() { }
}
C#SelectWhereLINQ
- Where: Filters elements based on a condition. - Select: Projects elements into a new form. Example:
var numbers = new[] { 1, 2, 3, 4 };
var even = numbers.Where(n => n % 2 == 0);
var doubled = numbers.Select(n => n * 2);
C#FuncDelegateDelegates
- Func: Predefined delegate with return type. - delegate: Custom delegate type definition. Example:
Func f = s => s.ToUpper();
delegate string MyDelegate(string s);
C#Static ConstructorClass Initialization
A static constructor initializes static members, called automatically before first use. Example:
class MyClass {
static MyClass() { }
}
C#Fibonacci SeriesAlgorithms
Check if a number is a Fibonacci number by generating terms or using the property that a number is Fibonacci if 5n^2 + 4 or 5n^2 - 4 is a perfect square. Example:
bool IsFibonacci(int n) {
int a = 0, b = 1;
while (a < n) {
int temp = a;
a = b;
b = temp + b;
}
return a == n;
}
C#BoxingUnboxingNullable Types
Boxing a nullable type boxes the underlying value if it has one; if null, it boxes to null. Unboxing requires type matching. Example:
int? x = 10;
object o = x; // Boxed to int
int? y = (int?)o;
C#Yield KeywordIterators
The `yield` keyword creates an iterator, returning elements one at a time, useful for lazy evaluation. Example: