DCSIMG
Some notes about Implicitly typed variables - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

Some notes about Implicitly typed variables

During some C# LINQ  project i have discovered some limitations and some things that can be done when working with the var new syntax,Here is a brief summery:

  1. When declaring a variable , you must assign its value on the declaration line.
    //Implicitly-typed local variables must be initialized
    var someVariable;
  2. Again:  must be done exactly when declaring
    //Implicitly-typed local variables must be initialized
    var someVariable;
    someVariable = 1;
  3. Cannot assign null as an Initial value
//Cannot assign <null> to an implicitly-typed local variable
 var oObj = null;
  4. However, after initialized can be null.
var oObj = new Object();
oObj = null;
  5. It is permitted to return a var value as long as the function is typed, such as:
     private int GetNumber()
     {
       var x = 5;
       return x;
     }

    6. Another limitation is , you cannot define a class member as var!!!

    

Comments

pavely said:

Most of these are not limitations.

How can you assign null to var - how would the compiler infer the type? it can't.

var just means - the compiler infers the type. It's fully type like any other variable.

# October 6, 2008 4:16 AM

Pini Dayan said:

Most of the things i mentioned are limitations, some of them are notes.

One may thing assigning null to a var would be permissible, that's why i mentioned it.

# October 6, 2008 4:41 AM

Dor said:

I don't understand why they have added all the C# 3.0 features. most of them, while saving some lines of code during writing, make it problematic to debug/understand/maintain the code.

I don't see any reason to use var instead of the normal type.

# April 2, 2009 10:19 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: