Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of var and default for declaration in C#

Tags:

c#

var

default

Recently I saw a person heavily using var and default keywords for declaration of variables (and for every declaration), something like this:

var employee = default(Employee);   //Employee is a class
var errorInfo = default(ErrorInfo); //ErrorInfo is struct; Blank is default value
var salary = default(Double);
var isManager = default(Boolean?); 

instead of using:

Employee employee = null;           //Employee is a class
ErrorInfo errorInfo = Blank;        //ErrorInfo is struct; Blank is default value
Double salary = 0.0;
Boolean? isManager = null;

or, instead of using even:

Employee employee;                  //Employee is a class
ErrorInfo errorInfo;                //ErrorInfo is struct; Blank is default value
Double salary;
Boolean? isManager;

Now using var and default for declaration for every variable is something i am not accustomed to.

Want to know:
- If this is a recommended practice?
- Your views and preference?

PS:
- Have gone through Use of var keyword in C#, Use of "var" type in variable declaration and https://stackoverflow.com/questions/633474/c-do-you-use-var, however, think that this question although related is slightly different as it is solely around declaration/initialization and not around assignment.
- I understand the difference between snipped 2 and snippet 3. However, question is more around snippet 1.
- If you strongly feel that this question belongs to programmers stackexchange feel free to move.

like image 838
publicgk Avatar asked Sep 06 '11 11:09

publicgk


People also ask

What is default value of variable in C?

value − Any value to initialize the variable. By default, it is zero.

What is variable declaration in C?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.

What is the default value of variable?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null. All member variables of a Newed object should be assigned a value by the objects constructor function.


1 Answers

I'm not going to say anything about "var" there have been comments and discussions about this in the past (sufficiently so ;-)

Concerning "default()" I would not use this to initialize a known type, but rather only in generics. There it helps to transparently handle value types or reference types by allowing you to provide a default (return) value or can be used in comparisons.

like image 160
Christian.K Avatar answered Oct 27 '22 04:10

Christian.K