In C#, what does declaring PriceChanged with the event keyword change compared with exposing a public delegate field of the same type?
answer
- what outside code may still do
- only two operators survive
- who may raise it
- error CS0070 outside the declaring type
basics
~10 sThe event keyword limits code outside the declaring type to += and -=. A public delegate field also lets any caller overwrite every subscriber with = or null and raise the notification itself.
solid answer
~30 sA public delegate field such as `public Action<decimal>? PriceChanged;` is just a field: any caller can assign it with `=`, which silently drops every other subscriber, set it to `null`, or invoke it and fake a price change. Declaring `public event EventHandler<PriceChangedEventArgs>? PriceChanged;` keeps the same delegate type but gives outside code only `add` and `remove`, reached through `+=` and `-=`. Anything else from outside the declaring type, including from a derived class, is error CS0070. Inside the class the field-like event still reads like a field, so the publisher alone decides when to raise it, typically with `?.Invoke`.
code
csharp · 16 linesvar ticker = new StockTicker();
ticker.PriceChanged += p => Console.WriteLine($"dashboard A: {p}");
ticker.PriceChanged += p => Console.WriteLine($"dashboard B: {p}");
// Nothing stops outside code from doing either of these to a public delegate field:
ticker.PriceChanged = p => Console.WriteLine($"rogue: {p}"); // replaces both subscribers
ticker.PriceChanged(0m); // raises the "event" from outside
ticker.Update(101m);
class StockTicker
{
public Action<decimal>? PriceChanged; // a public delegate field, not an event
public void Update(decimal price) => PriceChanged?.Invoke(price);
}go deeper
Remember the one rule: outside its class an event allows only += and -=. Assigning it, nulling it or invoking it from elsewhere is a compile error.
Explain the hazards of the public delegate field: = drops other subscribers, null unsubscribes everyone, and any caller can fake a raise. Name CS0070 and the declaring-type exemption.
Show the consequences in review: subclasses raise through a protected virtual OnXxx method, and changing a public field into an event later is a binary-breaking API change for compiled callers.
Frame the API choice: a stored delegate is a single owner-chosen callback, an event is a subscription surface. Pick per member and keep public delegate fields out of public APIs.
## Two declarations that look almost identical A **delegate** is an object that holds a reference to one or more methods; a delegate-typed field is just a field that stores one. An **event** is a class member, declared with the `event` keyword, whose type is a delegate type. In source the two differ by one word: ```csharp public Action<decimal>? PriceChanged; // public delegate field public event EventHandler<PriceChangedEventArgs>? PriceChanged; // field-like event ``` The second form is a **field-like event**: the compiler generates a private backing field of the delegate type plus two accessor methods, `add_PriceChanged` and `remove_PriceChanged`. Outside the class, the name `PriceChanged` no longer refers to the field at all; it refers to the event, and the only operations an event offers are *add a handler* and *remove a handler*. ## What outside code can do with each Picture a stock-ticker class that dashboards subscribe to. | Operation from another type | Public delegate field | `event` member | |---|---|---| | `ticker.PriceChanged += handler` | allowed | allowed (calls `add`) | | `ticker.PriceChanged -= handler` | allowed | allowed (calls `remove`) | | `ticker.PriceChanged = handler` | allowed, replaces all subscribers | error CS0070 | | `ticker.PriceChanged = null` | allowed, unsubscribes everyone | error CS0070 | | `ticker.PriceChanged(...)` or `?.Invoke(...)` | allowed, raises it from outside | error CS0070 | | read it, call `GetInvocationList()` | allowed | error CS0070 | The compiler's message for every row marked as an error is the same: > CS0070: The event 'StockTicker.PriceChanged' can only appear on the left hand side of += or -= (except when used from within the type 'StockTicker') ## Why the field is a real hazard The delegate field fails in ways that look like ordinary code: - **A typo destroys subscribers.** `ticker.PriceChanged = OnPrice;` instead of `+=` compiles and silently removes every dashboard that subscribed earlier. - **Anyone can raise the notification.** A caller can invoke the field with a made-up price, so subscribers can no longer trust that the publisher sent it. - **Anyone can inspect who is listening.** Reading the field exposes the invocation list, coupling outside code to other subscribers. - **Encapsulation is gone for good.** Changing a public field to a property or an event later is a binary-breaking change for compiled callers, because the member kind changes. The event keeps the publish-subscribe contract in one place: subscribers manage only their own handler, and the publisher alone decides when to raise. ## What stays the same inside the class Inside the declaring type, a field-like event behaves like its backing field. The class can raise it with `PriceChanged?.Invoke(this, e)`, test it for `null`, assign it, or clear it with `PriceChanged = null`. Two limits are worth knowing: 1. **Derived classes are outside.** A subclass that writes `PriceChanged?.Invoke(...)` gets CS0070 too, because the exemption is only for the declaring type. The .NET convention is a `protected virtual` method named `OnPriceChanged` that raises the event, so derived classes call or override that instead. 2. **Custom accessors remove the field.** When an event declares its own `add` and `remove` bodies, there is no compiler-generated backing field, so even the declaring class can only use `+=` and `-=` on the event name (error CS0079) and must raise the delegate it stores itself. ## What the event keyword does not do The keyword restricts *access*; it does not change delegate semantics: - The handlers still run synchronously, one after another, on the thread that raises the event. - The event is still multicast: subscribing the same handler twice means it runs twice. - It does not stop subscriber leaks; a publisher that outlives its subscribers still keeps them reachable, which is covered in the lesson on handler leaks. - It does not make raising thread-safe on its own; reading the delegate once with `?.Invoke` is a separate habit. ## When a delegate field or parameter is still right A delegate is the right tool when there is exactly one callback the owner chooses, such as a `Func<decimal, decimal>` pricing rule passed to a constructor or a callback parameter on a method. Then assignment *is* the intended operation. An event is right when many independent parties subscribe and unsubscribe to notifications that only the owner raises. Interviewers usually want that distinction in one line: a delegate is a value you pass or store; an event is a member that lets other code subscribe to a delegate it does not control.
- Can a class derived from StockTicker raise the base class's field-like PriceChanged event directly?No. The exemption in CS0070 covers only the declaring type, so `PriceChanged?.Invoke(this, e)` in a subclass does not compile. The base class exposes a `protected virtual void OnPriceChanged(PriceChangedEventArgs e)` that raises the event; the subclass calls it, or overrides it to react first and then calls `base.OnPriceChanged(e)`.
- Inside StockTicker itself, what can code do with a field-like PriceChanged event that outside code cannot?Inside the declaring type the name binds to the compiler-generated backing field, so the class can invoke it, compare it with `null`, assign it and clear it with `PriceChanged = null`. That is why the class alone can raise the event. It stops being true once the event declares custom `add` and `remove` accessors, because then there is no generated field.
- Does making PriceChanged an event change how its handlers run when it is raised?No. An event uses the same delegate type and the same invocation: handlers run synchronously, in subscription order, on the thread that raises it, and an exception in one handler propagates to the raiser. The keyword changes who may touch the delegate, not how it is called.
- An event and a public delegate field behave the same, the keyword is only documentation.
- Outside code can raise an event if it has a reference to the publisher.
- Derived classes can invoke a base class's field-like event directly.
- Assigning an event with = from another class replaces its handlers.
- The event keyword makes raising and subscribing thread-safe by itself.