4 Replies - 700 Views - Last Post: 15 February 2010 - 09:42 PM Rate Topic: -----

#1 Garigamo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 15-February 10

using new to create an object with defaults

Posted 15 February 2010 - 03:16 PM

Could some explain to me why use the new keyword when creating a object with the default constructor? Is there a difference which this:

MyClass Employee1 = new MyClass();

versus this:

MyClass Employee1;
Is This A Good Question/Topic? 0
  • +

Replies To: using new to create an object with defaults

#2 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7482
  • View blog
  • Posts: 15,504
  • Joined: 16-October 07

Re: using new to create an object with defaults

Posted 15 February 2010 - 03:19 PM

Sure, in C#, these are the same.
MyClass employee1;

MyClass employee1 = null;



Until you create an instance and assign it to a variable, an object variable has nothing.
Was This Post Helpful? 0
  • +
  • -

#3 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: using new to create an object with defaults

Posted 15 February 2010 - 04:40 PM

Just to add a little to what baavgai said. Classes are reference types in C#. What that means is that the variable that references an instance of a class points to where the data of the class is held in memory. Static items of the class all have the same position in memory and are shared between all instances of the same class. Until you create an instance of the class, using the new keyword, the variable points to nothing and has the value null If you try and assign something to the variable, call a method, etc, you will get an exception because there is not an instance of the class to work with.
Was This Post Helpful? 0
  • +
  • -

#4 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Re: using new to create an object with defaults

Posted 15 February 2010 - 07:21 PM

New invokes the default constructor and creates an instance of that class.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_Garigamo*


Reputation:

Re: using new to create an object with defaults

Posted 15 February 2010 - 09:42 PM

Good deal…thanks for everyones' reply. I understand now :bigsmile:
Was This Post Helpful? 0

Page 1 of 1