-8

I have this doubt in my mind for a very long time. May be this is the right forum to ask..

Is there any difference between the two types of variable declaration in C#. If so what is the difference and which is the best practice.

  DataTable dt;

vs

  DataTable dt=new Datatable();
DineshKumar
  • 487
  • 3
  • 12
  • 5
    Pretty sure this is a duplicate (which I will look for in a minute) but in the second one, you assign a value – Sayse Sep 17 '14 at 06:55
  • 2
    first one is creating a variable that can hold a datatable, the second creates the variable and instantiates it also. – Mark Hall Sep 17 '14 at 06:56
  • http://msdn.microsoft.com/en-us/library/aa691171%28v=vs.71%29.aspx – Tobi Sep 17 '14 at 06:58
  • [Related (See Reed Copsey's answer)](http://stackoverflow.com/questions/952503/c-sharp-variable-initialization-question).. still can't find duplicate (yet) – Sayse Sep 17 '14 at 07:02
  • [Another related](http://stackoverflow.com/questions/14511963/declaring-value-types-by-using-operator-new) – Sayse Sep 17 '14 at 07:05

4 Answers4

4

First one you are only declaring and in second you declaring and initializing. If you use any instance of a class without initializing, then you will get null reference exception as Object reference not set to an instance of an object

Community
  • 1
  • 1
Bharadwaj
  • 2,535
  • 1
  • 22
  • 35
0

http://msdn.microsoft.com/en-us/library/ms173109.aspx

if DataTable is a struct they are the same

if not DataTable dt; means create empy reference to a DataTable named dt; 'new Datatable();' means init the reference using Datatable object from the garbage collector

Nahum
  • 6,959
  • 12
  • 48
  • 69
0

In my opinion the best practice is to always initialize the variable in the constructor and never in the declaration. This is for consistency mainly, if you want to see how a type is initialized you should always only have to look in the constructor.

Daniel Persson
  • 2,171
  • 1
  • 17
  • 24
0

The first dt can hold a DataTable or object that inherites DataTable, the value of the first dt will be null after the first one is done.

The second dt can hold a DataTable or object that inherites DataTable, You initiated it with empty constructor of DataTable therefore it will not be null.

"Best Parctice" is depends on what you want to do with dt. for example, if you have a method on the next line that returns a new initiated DataTable it is not nessesery to initiate an instance that will not be used.

yossico
  • 3,421
  • 5
  • 41
  • 76