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;