I don't understand why we need the 'new' keyword

后端 未结 6 616
情话喂你
情话喂你 2020-12-02 18:19

I am new to C#, from a C++ background. In C++ you can do this:

class MyClass{
....
};
int main()
{
   MyClass object;         


        
6条回答
  •  忘掉有多难
    2020-12-02 18:58

    When you use referenced types then in this statement

    Car c = new Car();
    

    there are created two entities: a reference named c to an object of type Car in the stack and the object of type Car itself in the heap.

    If you will just write

    Car c;
    

    then you create an uninitialized reference (provided that c is a local variable) that points to nowhere.

    In fact it is equivalent to C++ code where instead of references there are used pointers.

    For example

    Car *c = new Car();
    

    or just

    Car *c;
    

    The difference between C++ and C# is that C++ can create instances of classes in the stack like

    Car c;
    

    In C# this means creating a reference of type Car that as I said points nowhere.

提交回复
热议问题