codecandle logo




 

C# - Basics - Variables - Type interference


Related: C# Tutorial

Date: 11.09.2011

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:
C# - Basics - Variables - Type interference



Area: articles

Reference resources: http://msdn.microsoft.com/en-us/library/ms364047%28v=vs.80%29.aspx
Tags: C# - Type Inference

Catagory layer 1: Programming
Catagory layer 2: Languages

Code layer 1: Languages
Code layer 2: csharp
Code layer 3: Basics
Code layer 4: variables
Code layer 5: type-inference

Reader layer 1: beginner

Sector layer 1: C# programmer

Fuzzy layer 1: What is type inference in C#
Fuzzy layer 2: Rules of type inference in C#

Nodes: Languages\C# (1)
  • comment icon
  • Comments Section
  • Post your Comment:


Chat section


[ Copy this | Start New | Full Size ]

CodeCandle

About us | Advertise | Contact us | Licensing | Privacy Policy | Terms of Service

© 2010 CodeCandle. All rights reserved.