Search This Blog


C# 3.0 Tutorial -1:Var Keyword

Var keyword

you can now declare a veriable with the "var" keyword where you dont need to mention the datatype

var Hello = "hello Programmer";
var my number = 42;

At first glance, it appears that you’re declaring a variable of type “var”. Actually, "var" is not a type, but rather a new keyword that means, “I want to declare a variable, but I’m too lazy to write out its type”. For cases where the type is "Dictionary<int, List<int>>" or similar, this saves quite a bit of clutter in the code:
// Before:
Dictionary<int, List<int>> Coeffs = new Dictionary<int, List<int>>();
// After:
var Coeffs = new Dictionary<int, List<int>>();

Following is a code snippent of Var keyword (code is done within an aspx page of a WebSite application)

using System;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class CSharp3_VarKeyword : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
/*var name = 22; name = "manab";//will throws error or var name;name="Manab"; will also throws error*/
var name = "Manab";
var answer = 42;
var prog = new DataSet();
var Friends = new List<string>();
var coeffs = new Dictionary<int, List<string>>();
var array = new[] {2,3,4,5,6,7 };
Response.Write("name is of type " + name.GetType().Name + "<br/>");
Response.Write("answer is of type " + answer.GetType().Name + "<br/>");
Response.Write("prog is of type " + prog.GetType().Name + "<br/>");
Response.Write("Friends is of type " + Friends.GetType().Name + "<br/>");
Response.Write("coeffs is of type " + coeffs.GetType().Name + "<br/>");
Response.Write("array is of type " + array.GetType().Name + "<br/>");
Response.Write("array element is of type " + array[2].GetType().Name + "<br/>");

bool condition = false;
var setCondionality =condition? new a():new b();
Response.Write("set Condionality is " + setCondionality.GetType().Name);

public class a { }
public class b :a{ }


And the output of the above prograp is as follows

name is of type String
answer is of type Int32
prog is of type DataSet
Friends is of type List`1
coeffs is of type Dictionary`2
array is of type Int32[]
array element is of type Int32
set Condionality is b

I consider that an improvement, both to developer productivity when writing code and to those reading the code too.

tags:what is var keyword in 3.0/3.5

No comments: