Understanding of Var Keyword In c#

Introduction

Hi all . before starting this article i wanted to say that this article is all about "Var" and this is very interesting keyword used in c#.
Those who wanted to improve their skill and wanted to go deep into c# programming , this article for them.


Get Started

Before dive into this topic lets discuss few more about "Var".
"Var" use the concept of early binding where the type assigned to "Var" will be identified in compile time. Lets discuss all feature of "Var" one by one and ll see in action.

Lets started ...........


Description

As i told above "Var" is used the concept of early binding. This mean when we are assign a value Lets say Integer as below.

var ivar = 10;

At compile time compiler check the value(10) which is an integer. Then "Var" converted to Integer. But remember once you assign a specific type you can not reassign other type lets say string to "Var".
Lets see in action.

Fig-1

See the above (Fig-1) i added 2 values to val1 and val2 to "Var". But you can see both the variable behave differently based upon the value supplied. But if i try to assign a "string" to "val1" then we ll get compiler error, because compiler already assign the val1 to "integer" type. Let see the action below.

Fig-2









In Fig-2 As Var1 is already treated as integer integer it can not converted to String.
Important points to Remember About "Var"
  1. "Var" is a keyword which only be used as a local variable to a method but cannot be used as a class variable . 
  2. Var cannot be used as a return type of a method.
  3. Need to assign a value while declaring Var keyword.
  4. If we do not know the type then we should go for "Var".
  5. It follows early binding concept.
  6. Its not a datatype it just a keyword which convert to datatype based upon the value assigned to it.

Thanks......


Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts