Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using var dataType in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 242
    Comment on it

    What and why we need to use Var dataType? This is one simple question that many of us might not know. So here it is, illustrated with a simple example:

    When we declare any variable as int i = 0; this is an explicit conversion. But when we write var i = 0; this is as implicit conversion, that means that the compiler looks for the data assigned during declaration and accordingly assign appropriate dataType to it. When you are declaring any variable as var you can't assign it as null.

    The most important use of var is due to LINQ. Lets discuss this with an example: First we will crate an example code of LINQ without using var.

    class Details  
    {  
        public int Length;  
        public string Value;  
    }  
    class LINQ  
    {  
        static void Main(string[] args)  
        {  
            string[] Names = { "Sandeep", "Abhay", "Ritesh" };  
            IEnumerable<Details> details = from x in Names select new Details  
                {  
                    Length = x.Length, Value = x  
                };  
            foreach(Details d in details)  
            {  
                Console.Write(string.Format("Name : {0}, Length : {1}\n", d.Value, d.Length));  
            }  
            System.Threading.Thread.Sleep(2000);  
        }  
    }
    

    In the above code, we have created a strongly typed object which we can get from a LINQ query. But the line of code is a lot i.e we created a class, then put this class in IEnumerable and then getting the property.

    Now we will use the same above example with var.

    class LINQ  
    {  
        static void Main(string[] args)  
        {  
            string[] Names = { "Sandeep", "Abhay", "Ritesh" };  
            var v = from x in Names select new  
                {  
                    Length = x.Length, Value = x  
                };  
            foreach(var d in v)  
            {  
                Console.Write(string.Format("Name : {0}, Length : {1}\n", d.Value, d.Length));  
            }  
            System.Threading.Thread.Sleep(2000);  
        }
    }
    

    As its self explanatory using var the same can be achieved simply with less code. The biggest advantage of using var with LINQ and Anonymous time is that we do not need to create class "Details" anymore.


    Happy Coding.....


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: