Differences in Default Naming of a control for WP7 in Expression Blend and Visual Studio

C# Tips & Tricks #27 – 5 things that you cannot do with var keyword

The Local Type Inference is also called as Implicitly Types Local Variables in C# and is an easy way to create a variable without having to know the type. In this blog post , let’s have a look at important things that you cannot do with this feature in C#.

This is especially useful when using a LINQ via the var keyword . The var keyword only works with the local scope , you cannot return or reference a variable created with the var ouside the scope of the local method.

5 things that you cannot do with a Local Type Inference in C#

1. You cannot Create a Private field with var like

 class Employee
 {
        var EmployeeName;
 }

You might get the following error , when you build the application

“The contextual keyword ‘var’ may appear only within a local variable declaration .That means , you can only use this in the context of the method .

2. You cannot use var as the input parameter like

 public void SetData(var EmployeeParameter)
 {
 }

and you will end up getting the same error again .

3. You cannot use var as a return type

public var GetData()
{
}

4. The Implicit-types local variables has to be initialised with value when declared .

5. You cannot assign null value to the implicit variables .like

var variable1=null;

    2 Comments

  1. Sane
    May 19, 2010
    Reply

    6. You can not use var to define lambdas:
    var f = x=>x+2;

  2. May 19, 2010
    Reply

    Hey San ,
    Never knew this . Thanks for the info

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...