Powered by Blogger.

Saturday, February 22, 2014

Implicitely typed variables in C#.Net

In this post we will discuss about Implicitely  typed  variables in C#.Net. Also you can check my previous posts on:

- Delete all stored procedures at once in SQL Server database

- How to set enum values with spaces in c#.net?

- Display Favicon in Asp.Net web site

It was a feature added in c#3.0 which allows to declare a variable using "var" keyword.

The  datatypes  of the variable will be decided depending upon the value we assign to the variables.

We can not declare a variable using "var" without assigning a value. The "var" keyword  may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

Multiple implicitly-typed variables cannot be initialized in the same statement.

Below  are  some examples:
// i is compiled as an integer
var i = 50;

// s is compiled as a string
var s = "aspdotnethelp"

// x is compiled as int[]
var x = new[] { 0, 1, 2 ,3};

// expr is compiled as IEnumerable<Customer>  or IQueryable<Customer>

var expr =
    from c in customers
    where c.Name == "AspDotNetHelp"
    select c;

// list is compiled as List<int>                            
var list = new List<int>();

// b is compiled as boolean
var b = false;

// anon is compiled as an anonymous type
var anon = new { Name = "Bijay", Age = 31 };

// invalid

Using System;
Class  ImplicitelyTyped
Static Void Main ()
Var  a = 200;
Console.WriteLine (a.GetType ());
Var  f = 3.14f;
Console.WriteLine (f.GetType ())
Var  s = "aspdotnethelp";
Console.WriteLine (s.GetType ());

System. Single
System. String

NOTE:  GetType () is a predefined method which returns the type of given variable type or object.


Post a Comment