Type Interference
Type inference in C# enables compiler to infer the type of the variable.
How type inference works in C#
Compiler uses type inference to find out which type of variables is from its initialized value. Example:
int v_aVariable = 5; //declares an Integer variable and is initialized to Integer///
var v_aVariable = 5; //declares an Integer variable and is initialized to Integer///
Above declared second variable is initialized into an Integer value. When it is compiled, it is interfered to INT32. Because compiler figures it out by what it is initialized to.
Notes about type intereference:
- Variable needs to be initialized (to let compiler figure out the type from initialized value)
- Initializer can not be "null"
- Initializer needs to be an expression
- Type of interfered variable can not be changed after it is inferred.
- Strong type rules of .NET applies to variable after inference.
Type inference example in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string [] args)
{
//declare and initialize variables for inference///
//initialize into an Integer type///
var x = 0;
//initialize into an String type///
var y = "nevada";
//to verify correct inference, we display the types of variables declared above///
//1th variable///
Console.WriteLine("Type of 1th variable is " + x.GetType());
//2nd variable///
Console.WriteLine("Type of 2nd variable is " + y.GetType());
//hook console window///
Console.ReadLine();
}
}
}
Console output: