Type Inference

Type Inference and the var Keyword

Take a look at the code below. The data type specified at the start of each variable declaration can be automatically determined by the compiler using the initialization value on the right side of the equals sign. For instance, can the compiler infer that 18 is an integer int, and that Phone() returns an object of type Phone?

static void Main( )
{
    int age = 18; // The value 18 on the right is inferred directly as int
    Phone p = new Phone(); // The constructor on the right returns a Phone instance
}
Code language: C# (cs)

With that in mind, can we simplify the code shown above?

C# offers the var keyword to shorten syntax as a replacement for explicit type declarations.

static void Main( )
{
    var age = 18;
    var p = new Phone();
}
Code language: JavaScript (javascript)

Every variable on the left uses var here. The compiler figures out the appropriate type from the right-hand expression. After compilation, both versions of the code are identical.

Important Notes

  1. var is not a dynamic type. It is merely syntactic sugar. The compiler locks in the inferred type at compile time and the type cannot be changed afterwards; both code snippets behave exactly the same.
  2. Mandatory rules when using var:
    • It works only for local variables, not class instance fields
    • You must assign an initial value upon declaration. Writing only var x; is invalid
    • The inferred type remains fixed. You cannot later assign values of different types to the variable
  3. Key distinction: var in C# ≠ var in JavaScript. JavaScript’s var implements dynamic weak typing, allowing variables to hold different data types at any time. C# var is just shorthand within a statically typed language and does not alter C#’s strong typing characteristics.

To elaborate: during compilation, the compiler interprets the var declarations above, setting age’s type to int and p’s type to Phone based on the right-hand values. The end result matches the first sample completely.

The variable types cannot be modified later. Take this example:

class Program
{
    static void Main()
    {
        var age = 18;
        age = 3.14;
        var p = new Phone();
    }
}

class Phone
{
    public string Name { get; set; }
}Code language: C# (cs)

This code produces an error in C#, but other languages such as JavaScript and PHP permit this practice, letting variables switch data types freely.

JavaScript and PHP fall under weakly typed, dynamically typed languages where variables carry no permanent type restrictions.

Invalid Example


class Program
{
    static void Main()
    {
        var age = 18;
        age = 3.14;
        var p = new Phone();

        var isBuy;
    }
}

class Phone
{
    var price = 1000;
    var model = "iPhone";

    int count = 12;
}Code language: C# (cs)

Type Inference

Leave a Reply

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