Your second example declares a variable, but it will be empty and can't be accessed:
Box b;
int id = b.Id; // Compiler will tell you that you're trying to use a unassigned local variable
We can fool the compiler by initializing with null:
Box b = null; // initialize variable with null
try
{
int id = b.Id; // Compiler won't notice that this is empty. An exception will be trown
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex);
}
We see now, that we have to initialize the variable in order to access it:
Box b; // declare an empty variable
b = new Box(); // initialize the variable
int id = b.Id; // now we're allowed to use it.
Short version of declare and initialize is your 1st example:
Box b = new Box();
Here the example-class i used for the examples:
public class Box
{
public int Id { get; set; }
}
Perhaps you did notice that Id
in our Box
is not being initialized. This is not needed (but most times you should do) because it is a value-type (struct
) and not a refenrence-type (class
).
If you want to read more, have a look at this Question: What's the difference between struct and class in .NET?