Inno 3.7 Delegates Flashcards
(30 cards)
What is a delegate in C#?
A delegate is a type that represents references to methods with a specific parameter list and return type.
It provides type-safe method pointers. You can invoke a delegate to call the method(s) it references.
Delegates are commonly used for callbacks and event handling.
How do delegates enable callbacks in C#?
Delegates store method references that can be called later, making them perfect for callbacks. For example, a method can accept a delegate parameter and call it when a specific operation completes. This allows asynchronous or event-driven programming. It helps decouple logic by passing behavior as a parameter.
What is a multicast delegate?
A multicast delegate holds references to more than one method. When invoked, all methods in the invocation list are executed in order.
Only the last method’s return value is retained if the delegate has a return type. They’re useful in event broadcasting where multiple listeners respond.
What are anonymous delegates?
Anonymous delegates are inline method definitions without a named function. They were introduced before lambda expressions in C#. You can declare them with the delegate keyword directly inside method calls or assignments. They allow for concise code when the logic is simple and localized.
How do lambda expressions relate to delegates?
Lambdas are shorthand for anonymous methods and are converted into delegate instances by the compiler. For example, (x) => x + 1 can be assigned to a delegate like Func<int, int>. Lambdas are a core part of LINQ and functional-style programming in C#.
What is the Action delegate in C#?
Action is a built-in delegate that represents a method that returns void and can have 0 to 16 input parameters. It’s commonly used when you need to execute code but don’t care about returning a value.
Example: Action<int> log = x => Console.WriteLine(x);</int>
What is the Func delegate in C#?
Func is a built-in delegate for methods that return a value. It can take up to 16 input parameters, and the last type parameter defines the return type.
Example: Func<int, int, int> add = (x, y) => x + y; returns the sum of two integers.
What is the Predicate delegate in C#?
Predicate<T> is a built-in delegate that takes a single input of type T and returns a **bool** . It's often used in filtering logic like List<T>.Find or List<T>.RemoveAll. Example: Predicate<int> isEven = x => x % 2 == 0;</int></T></T></T>
RETURN A BOOL
What are memory leaks related to delegates?
Memory leaks can occur when annobject subscribes to events but is never unsubscribed, keeping it in memory.
The event publisher holds a reference to the subscriber, preventing garbage collection. Always unsubscribe from events (especially static ones) when the object is disposed or no longer needed.
What is a closure in C#?
A closure is a function that captures variables from its enclosing scope.
W C#, kiedy tworzysz funkcję wewnętrzną (np. lambda lub anonimowy delegat), ta funkcja może korzystać z zmiennych zewnętrznych (czyli zmiennych, które były dostępne w kontekście, w którym ta funkcja została zadeklarowana). Closure zapewnia, że te zmienne są przechowywane w takim stanie, w jakim były w momencie tworzenia funkcji, a nie w momencie jej wywołania.
In C#, lambda expressions and anonymous methods can close over local variables. These captured variables live beyond their original scope, which can lead to subtle bugs if not understood properly.
CAPTURE VARIABLES OF ORIGINAL SCOPE
Can closures lead to unexpected behavior in loops?
Yes, closures can capture loop variables in unexpected ways. For example, a lambda inside a for loop may capture the loop variable by reference, not by value. This can result in all lambdas using the final value of the loop variable unless a local copy is created inside the loop.
What is covariance in delegates?
Covariance allows a method to have a more derived return type than that defined in the delegate type. For example, if a delegate returns an Animal, you can assign it a method that returns Dog. This makes delegate assignment more flexible.
METHOD CAN RETURN ITS RETURN TYPE AND THE TYPE THAT INHERITS THIS TYPES
What is contravariance in delegates?
Contravariance allows a delegate to accept parameter types that are less derived than specified in its signature. For instance, if a delegate expects a Dog parameter, it can point to a method that accepts Animal. This is useful for broader compatibility when consuming input.
DELEGATE CAN ACCEPT THE TYPE LESS DERIVED
How do you declare variance in generic delegates?
You use out for covariance (return types) and in for contravariance (input types) in generic delegate definitions. Example: delegate TResult MyFunc<out>() or delegate void MyAction<in>(TInput input). It ensures safe and flexible type assignments.</in></out>
What is an event in C#?
An event is a special delegate field that supports the publisher-subscriber model. It restricts invocation to the declaring class. Events provide a mechanism for broadcasting changes in object state to registered listeners (subscribers), enhancing decoupling in application logic.
SPECIAL DELEGATE FILED IN PUBLISHER-SUBSCRIBER MODEL
How is an event declared and raised?
You declare an event using the event keyword and a delegate type. Example: public event Action SomethingHappened;. You raise (invoke) the event from within the class using SomethingHappened?.Invoke();, checking for null to ensure subscribers exist.
What is the standard .NET event pattern?
The standard .NET event pattern uses EventHandler or EventHandler<T> with two parameters: object sender and EventArgs e. It allows subscribers to know who raised the event and carry additional event data. Example: public event EventHandler MyEvent;</T>
What are EventArgs in .NET?
EventArgs is the base class for event data in .NET. You can subclass it to carry custom data for specific events. It helps maintain a consistent and type-safe way of passing information to event handlers.
How does the Publisher-Subscriber pattern work with events?
In the Publisher-Subscriber pattern, the publisher class defines and raises events, while subscriber classes register methods (handlers) to those events. When the event is raised, all subscribed methods are invoked, allowing subscribers to react to the publisher’s state changes.
What is the difference between a delegate and an event?
A delegate is a type representing a method reference, while an event is a controlled wrapper around a delegate. Events prevent external classes from invoking the delegate directly. Delegates are flexible; events enforce encapsulation in the publisher-subscriber model.
What happens if an event has no subscribers when it’s raised?
If an event has no subscribers, invoking it without checking for null results in a NullReferenceException. The recommended pattern is using null-conditional invocation: MyEvent?.Invoke(this, EventArgs.Empty); to safely raise the event only if subscribers are present.
How do you unsubscribe from an event?
To unsubscribe, use the -= operator with the same delegate instance that was used to subscribe. For example: myPublisher.MyEvent -= MyHandler;. This is crucial for preventing memory leaks, especially when subscribers outlive the publisher or use long-lived events.
Why are memory leaks common with events?
Events can cause memory leaks because the publisher holds strong references to its subscribers through delegate chains. If subscribers don’t unsubscribe, the garbage collector can’t collect them, even if they’re no longer in use elsewhere in the app.
How can weak references help with event memory leaks?
Using weak references or WeakEventManager (WPF) allows events to reference subscribers without preventing garbage collection.
This approach breaks the strong reference cycle between publishers and subscribers, helping avoid memory leaks without requiring manual unsubscription.
CAN REFERENCE SUBSCRIBERS WITHOUT PREVENTING GARBAGE COLLECTION