General C# Flashcards
(3 cards)
What are Generics in C# and why are they useful?
Generics in C# allow you to define classes, methods, interfaces, and delegates with type parameters, making them reusable and type-safe.
🔹 Why are they useful?
Eliminate Type Casting: Avoids runtime errors by enforcing type safety at compile time.
Improve Performance: Reduces boxing/unboxing for value types.
Enhance Code Reusability: A single generic class/method works with multiple data types.
Common Examples: List<T>, Dictionary<TKey, TValue>, and custom generic classes like Box<T>.</T></T>
What are Delegates in C# and why are they useful?
A delegate in C# is a type that represents a method signature, allowing methods to be passed as parameters, assigned to variables, and executed dynamically.
🔹 Why are they useful?
Encapsulate Methods: Store references to methods for flexible execution.
Enable Callbacks: Useful for event-driven programming (e.g., EventHandler).
Support Functional Programming: Used in LINQ, anonymous methods, and lambda expressions.
Common Examples: Action<T>, Func<T, TResult>, Predicate<T>, and custom delegates like delegate void MyDelegate(int x).</T></T>
What are Lambda Expressions in C# and why are they useful
A Lambda Expression in C# is a concise way to write anonymous functions, often used in delegates, LINQ, and functional programming.
🔹 Why are they useful?
Shorter & Readable Code: Replaces verbose anonymous methods.
Inline Function Definitions: No need for separate method declarations.
Widely Used in LINQ: Enables efficient data queries (list.Where(x => x > 10)).
Common Syntax:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25