Wednesday 17 October 2007

Part 4: Implicit types

With C#2, a variable's type must be explicitly declared, some simple examples are:

int clientAge;
string clientName = "Matthew";
DateTime currentDate = DateTime.Now;

Notice that we do not have to specify a value for the variable at the point at which it is declared, in the example, clientAge will be assigned a value of zero by the compiler. In C#3, variables may be declared with the var keyword in which case the compiler infers the variable type from the value it has been assigned...but it does this at compile time!

So var is not a variant (it's just a keyword that's not named particularly well) and it's not an object type either.

The following constraints apply to the use of the var keyword:

  • var can only be used within a method and not at the class level
  • Any variable created with var must have a value assigned as part of the declaration

Please see the following code for examples:

class VarSamples
{
    //This will not compile, the following error will be reported:
    //The contextual keyword 'var' may only
    //appear within a local variable declaration
    var invalidDeclaration;

    public void ImplicitTypes()
    {
        //The compiler will create postCode as a string variable
        var postCode = "B12 5HP";

        //The compiler will create postCode as an integer variable
        var houseNumber = 8;

        //This will not compile, the following error will be reported
        //Implicitly-typed local variables must be initialized
        var streetName;

        //Perform operations with var variables.
        int nextHouseNumber = houseNumber++;
        string formattedCode = "Postcode: " + postCode;
    }
}

The invalidDeclaration variable will not compile because it has been declared at the class level. This is not allowed for variables declared as var.

The streetName variable will not compile because any variable declared with var must be initialised when it is declared. Otherwise, the compiler is not able to determine an actual type for the variable when it is compiled.

So why do we need var at all?

The var keyword was introduced to support anonymous types that are also a feature of C#3. Anonymous types are described in the next article.

No comments: