this is a first of a series about new features in c# 3.0

all the programming languages have some kind of a machanism to store progrmatic data in c# there are two types called reference types and value types when we consider value types almost all the programming languages had implemented them as a part of their framework
Basically their are two types of value types 
static
dynamic

static typing
type of the variables are known in cmpile time this is the common practice in languages like c#, java, c, c++

int a=10;
string name="Dhanushka Sandaruwan Athukorala";

dynamic typing
here the variable comes with some kind of a tag that contains it type. when you assign a value to the variable at the run time this tag value is set to the type of this assigned value

the funny thing is every time an operation is performed the type will be checked to make sure that the operation is safe

for an example this will wok in dynamically typed code but not in static typing

a="Dhanushka Sandaruwan Athukorala";
if(true)
{
a=12;
}
b=a/2;

here as you can see when the devission occur a's type tag is set to int rather than string thats the magic of dynamic typing

now lets see what c# 3.0 offeres
var fullName="Dhanushka Sandaruwan Athukorala";
var age=22;
var arr=new[] {1, 2, 3, 4}
hmm...
what's going on
at first you would say that "var" is just a new value type!!!
No sir!!! its not!!!
its just a new keyword introduced in c# 3.0 to indicate to the compiler that "i'm gona create a new variable, but i dont know about its type. so you just take care of it for me!!"

we all know that c# is a staticstically typed language, but yet it si offering a functionallity similar to a dynamically typed one???
whats the secret??
what happens here is a newly written type inferencing algorithm is used by the compiler(take this to note, which means this happens at compile time not at run time) goes through the code and finds out what's the type of the variables assigned to the "var" variables. which means that this is similar to an explicit declaration of a variable but you dont have to know the type of it.
for an instance if we referfullName.GetType()  and age.GetType() values at run time they will give string and int32 as their variable types

but their are some other issues you should be aware of when you use var 
you must  initialize a variable with a nonnull value when you declare it
this want compile
var a; var b=null;
a=18;
as a conclusion we can say although this will distance c# from being a simple language, it will enhance the developer productivity as well as code readability. 

0 comments:

Post a Comment