1

According to C# Reference

"The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables'

I was surprised to find out that
Commenting e=null line in the following app code (taken from the article "Difference Between Events And Delegates in C#") results in compilation error:

Use of unassigned local variable 'e'

while without commenting it is compiled and run.

I do not get:

  • Where is variable e used?
  • Is it possible to force the app to run without the dumb assigning the variable to null?

f

using System;   
class Program   
{   
  static void Main(string[] args)   
  {   
    DelegatesAndEvents obj = new DelegatesAndEvents();   
    obj.Execute();  
  }  
}  
public class DelegatesAndEvents  
{
  public event EventHandler MyEvent;
  internal void Execute()
  {
    EventArgs e;
//Commenting the next line results in compilation error
//Error 1   Use of unassigned local variable 'e'
    e = null;
    int sender = 15;
    MyEvent += MyMethod;
    MyEvent += MyMethod2;
    MyEvent(sender, e);
  }
  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
  }
  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}

Update (or the comment to all answers):
So, and I never knew it, there are to kind of nulls - one which is assigned and another which is not assigned... Funny...

They should probably have different types, for checking:
if typeof(unassigned-null) then do this;
if typeof(assigned_null) then do that;

Fulproof
  • 4,466
  • 6
  • 30
  • 50
  • 1
    Check Eric's and Mark's answers to very similar questions http://stackoverflow.com/questions/1423437/why-do-i-have-to-assign-a-value-to-an-int-in-c-sharp-when-defaults-to-0 and http://stackoverflow.com/questions/8931226/are-c-sharp-uninitalized-variables-dangerous/8933935#8933935 – Ilya Ivanov Feb 14 '13 at 13:39
  • `The reason this is illegal in C# is because using an unassigned local has high likelihood of being a bug` - Eric Lippert (From link above) – asawyer Feb 14 '13 at 13:42
  • `e` is used at the line `MyEvent(sender, e)`. The compiler does not do full analysis to determine that all subscribers ignore the `e` parameter. (Who knows. Since it's a public event, somebody else may have subscribed to `MyEvent` and that other person uses `e`.) – Raymond Chen Feb 14 '13 at 13:43
  • No, there aren't two kinds of nulls. You're just dealing with the definite assignment rules of C# - that say you **may** **not** read from a local variable that has not been assigned a value. This goes beyond the requirements of the CLR (which ensures that any reference variables will be `null` before the first assignment). Because, as @asawyer points out in their comment, forgetting to assign a value is a frequent source of bugs. – Damien_The_Unbeliever Feb 14 '13 at 15:00
  • @Damien_The_Unbeliever , that was a joke – Fulproof Feb 14 '13 at 15:11

4 Answers4

2

Local variables are not initialized with their default value, whereas fields are.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
  • Well, make sense, since local var is not accessible from outside. Changed `e` to field/property and the app started to run without (explicit) assignment to `null` – Fulproof Feb 14 '13 at 14:59
1

To answer your questions:

  • Question: Where is variable e used?

Answer: It is used where you pass it to MyEvent(sender, e);

  • Question: Is it possible to force the app to run without the dumb assigning the variable to null?

Answer: No, and it's not dumb because you ARE using e by passing it to another method. You are just not using it directly - but you are still using it.

Actually, you don't need to declare e anywhere - you can just pass null directly to MyEvent:

MyEvent(sender, null);

Then you don't need to do any redundant variable declaration.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Instead of `null` you may also use `EventArgs.Empty`, which would not fail if a consumer calls `Equals` or instance member. Off topic but worth mentioning anyway, imho. – Matthias Meid Feb 14 '13 at 14:52
  • Saw [Why use EventArgs.Empty instead of null?](http://stackoverflow.com/questions/188692/why-use-eventargs-empty-instead-of-null) but have not finished reading it yet – Fulproof Feb 14 '13 at 14:56
1

There's no way for the compiler to know, when compiling Execute what event handlers are registered to MyEvent. (Others may have already been registered before Execute is called, and they may attempt to use e). As such, it doesn't attempt any analysis on any handlers it could know are registered. So, since you want to pass e, it has to be initialized.

If you want to pass null, why introduce e at all? Just have

MyEvent(sender, null);

Which at least makes your intent explicit.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • Really, my intent is that I am currently searching the code examples demonstrating why the hell I am forced to always have event arguments at all. I cannot even find when and why they are always needed – Fulproof Feb 14 '13 at 14:42
  • 1
    @Fulproof Uhh.... you are reusing a specific delegate type, `EventHandler`. If you don't like it's arguments, *use a different delegate type.* – asawyer Feb 14 '13 at 14:44
  • @Fulproof - they aren't always *needed* - but they're part of a *recommended* pattern, because it's frequently observed that handlers want access to the object on which the event occurred (they may be listening to multiple objects) and that events frequently have additional information beyond "the event happened" to convey to handlers. – Damien_The_Unbeliever Feb 14 '13 at 14:46
  • @asawyer, Came to this question from [Difference Between Events And Delegates](http://softwarecafeblog.blogspot.ru/2012/06/difference-between-events-and-delegates.html) where explicit delegate was initially engaged but unuseв and unwarranted EventArgs var was still there – Fulproof Feb 14 '13 at 14:49
  • @Damien_The_Unbeliever, my real question was to understand the use of EventArgs, all the code and code examples I've seen lack its use. I did not ask just because I am afraid it is either dupe or stupid or too obvious... – Fulproof Feb 14 '13 at 14:52
1

You are using e without assigning a value to it. Using e = null;, you are assigning value to variable e as null is also a value.

Also, according to C# reference default value for reference types is null but here e is a variable. Variables are not defaulted, and must have "definite assignment" before they are used.

Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
  • Debugger shows me that before assignment the variable e to null it is also null... or what is it? – Fulproof Feb 14 '13 at 14:18
  • 1
    @Fulproof The debugger will show you the value of lots of things when they are not in scope or for some reason not technically value to access in code. It's simply looking at what the bits are in memory at that point in time and spitting them back out at you. – Servy Feb 14 '13 at 15:32