0

I started to learn C# and I found out that there are two different ways to create the object. First is this:

 Box Box1 = new Box();   // Declare Box1 of type Box
 Box Box2 = new Box();   // Declare Box2 of type Box

Other is this:

 Box Box1 ;   // Declare Box1 of type Box
 Box Box2 ;   // Declare Box2 of type Box

Both methods work, what is the difference? Is there something similar with C++ pointer?

Box* Box1 = new Box();   // Declare Box1 of type Box
Box* Box2 = new Box();   // Declare Box2 of type Box
πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183
Ah Tan
  • 39
  • 6

1 Answers1

3

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?

kara
  • 3,030
  • 4
  • 19
  • 31
  • You assume Box is a class. What if it is a Value Type instead? – Henk Holterman Apr 26 '19 at 08:53
  • Correct. Added an explaination for not initializing Id because it is a `struct`. I'll have a look for the Link to the MS Docs.. – kara Apr 26 '19 at 08:55
  • 1
    "Compiler will tell you that this is illegal, because "b" is "null"." - no, the compiler will tell you that this is illegal because the variable isn't *definitely assigned*. That's very different from it being defined with a null value. – Jon Skeet Apr 26 '19 at 08:59