Inno 3.7 Delegates Flashcards

(30 cards)

1
Q

What is a delegate in C#?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do delegates enable callbacks in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a multicast delegate?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are anonymous delegates?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do lambda expressions relate to delegates?

A

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#.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Action delegate in C#?

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the Func delegate in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the Predicate delegate in C#?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are memory leaks related to delegates?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a closure in C#?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can closures lead to unexpected behavior in loops?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is covariance in delegates?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is contravariance in delegates?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you declare variance in generic delegates?

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an event in C#?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How is an event declared and raised?

A

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.

17
Q

What is the standard .NET event pattern?

A

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>

18
Q

What are EventArgs in .NET?

A

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.

19
Q

How does the Publisher-Subscriber pattern work with events?

A

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.

20
Q

What is the difference between a delegate and an event?

A

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.

21
Q

What happens if an event has no subscribers when it’s raised?

A

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.

22
Q

How do you unsubscribe from an event?

A

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.

23
Q

Why are memory leaks common with events?

A

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.

24
Q

How can weak references help with event memory leaks?

A

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

25
Can a lambda expression be unsubscribed from an event?
Only if it is stored in a variable. Anonymous lambdas cannot be unsubscribed unless you hold a reference to the delegate. Example: EventHandler handler = (s, e) => { ... }; then subscribe and unsubscribe using handler.
26
Can multiple subscribers handle the same event?
Yes, an event can have multiple subscribers. When the event is raised, all subscribed methods are invoked in the order they were added. Each handler runs independently, but one throwing an exception can prevent others from executing if not handled
27
What is a custom EventArgs class and when would you use it?
You use a custom EventArgs class when you need to pass extra data with the event. Inherit from EventArgs and add properties. Example: public class PriceChangedEventArgs : EventArgs { public decimal NewPrice { get; } }
28
What is the difference between Action and Func delegates?
Action delegates return void and are used for methods with no return value. Func delegates return a value, with the last type parameter defining the return type. Use Action for side effects and Func for computations or data transformations.
29
What are the rules for method compatibility with delegates?
The method must match the delegate’s signature—same parameter types (in order) and return type. Covariance and contravariance can allow some flexibility with return and parameter types, but method and delegate signatures must still be compatible overall.
30
Can a delegate reference multiple static and instance methods?
Yes, a delegate can reference both static and instance methods in its invocation list. When invoked, it will call all methods regardless of whether they're static or tied to specific object instances. This is the essence of multicast delegates.