c# tutorials

Updated : Oct 05, 2020 in Articles

What is var data type in C#

Var data type: var data type is c# 3.5 features it is a compile-time variable. Based on the LHS value RHS expression will change at the time of compile type. Once a value will be assigned it will never change See the given examples for in detail.

Example:

class Program
    {
        static void Main(string[] args)
        {
            var val = 10; //it is type of integer 
            var str = "var data type in c#";
            var fl = 34.6f;
            Console.WriteLine(val.GetType());
            Console.WriteLine(str.GetType());
            Console.WriteLine(fl.GetType());
            Console.Read();
        }
    }

Output: System.Int32

              System.String

              System.Single

Example:

The given below example it will show you compile time error because of val alredy assigned value again we are trying to assign.

class Program
    {
        static void Main(string[] args)
        {
            var val = 50; //it is type of integer 
            var val = 10; // error compile time
           
            Console.WriteLine(val.GetType());
            Console.Read();
        }
    }

When we will use var data type?

In real-time we are dealing with objects at run Many times we don’t know at run time what type of data inside the variables will have at the time we will use var data type.var data type it will store all data type values like int, float, long, string, bool..etc.var is static ​

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x