C Sharp Var data type and Anonymous Type: An Overview

C Sharp Var data type and Anonymous Type: An Overview

23 May 2024
Intermediate
178K Views
16 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

Var data type and Anonymous Type in C#: An Overview

We know that datatypes in c# play a vital role in programming. But what if it is difficult to declare a variable's datatype when the type is not known? and also the code is too complex. To handle this problem, we have var data type and anonymous type in C#. In this C# tutorial, we will learn when to use var data type and anonymous type and how to use var data type and anonymous type.

What is the Var data type?

  • The keyword var is used to declare implicit type variables in C#, which means it tells the compiler to figure out the variable type at compilation time.
  • A var variable must be initialized at the time of declaration.
  • ​​var can contain any type of data. If you insert a number into a variable, it will be interpreted as a number if possible.
  • If you enter text, it will be interpreted as a string, etc. C# supports the variable type var since version 3.0.
  • In C# var is strongly typed.
  • Once a variable is declared, it can only have an initialized type.
  • Also, variables must be initialized before they can be declared.
  • Some arguments of variable type var require less input.
  • For example, it's shorter and easier to read than a dictionary.
  • var requires fewer code changes when the return type of a method call changes.
  • You only need to change the declaration of the method, not everywhere the method is used.

    Declaring Valid var statements:

    Let's elaborate on this in C# Compiler:

     using System;  
    using System.Text;  
    using System.Collections;  
    
    namespace ConsoleApplication1  
    {  
        class Program  
           {  
             static void Main(string[] args)  
                 {    
    
                  var str = "1"; 
                  var num = 0; 
                  string s2 = null; 
                  string s3 = null; 
                  var s4 = s3; 
               
                Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}", str, num , s2 , s3 , s4);  
               Console.Read();  
           }  
       }  
    } 
    Output
     10 
    Compiled statements
     string str = "1";0;
    string s4 = s3; 
    Once the var variable is initialized its data type becomes fixed to the type. At compile time, the above var statements are compiled to IL, Because the compile-time type value of the var variable cannot be null but the runtime value can be null. Hence the above program will compile but it gives only two variables output. In this, The correct type must be used to initialize var variables to assign values to variables. So you don't have to use var for simple local variables that are known to you. You can use var when you’re not sure what type of data will be stored in a variable.

    Read More - C# Interview Questions For Freshers

    Declaring the array with the var keyword in C#

     using System;
    using System.Text;
    using System.Collections;
    
    
    namespace ConsoleApplication1
    
    {
     class Program
      {
         static void Main(string[] args)
           {
               var aInt = new int[] { 5, 6, 3, 8,41, 2 };
               foreach (var item in aInt)
              {
                   Console.Write( item.ToString()+ Environment.NewLine);        
              }
                Console.Read();
            }
        }
    
    
    }    

    Output

     5
    6
    3
    8
    41
    2  
    Here, We can use the var keyword to declare array data types where we don't have predefined datatypes as shown in the above example. We can see here, how declaring an array with a var datatype does not bother with the type of data of each element in the array. But we have to just use a for each loop with one var variable to find all the elements in the array.

    Var application in the treatment of ArrayList

     using System;  
    using System.Linq;  
    using System.Text;  
    using System.Collections;  
     
    namespace ConsoleApplication1  
    {  
        class Program  
       {  
          static void Main(string[] args)  
          {  
               ArrayList list = new ArrayList();  
              list.Add("One");  
            list.Add("Two");  
               list.Add(3);  
             list.Add(4);  
               Console.WriteLine("Total: {0}\n", list.Count);  
               foreach(var a in list)  
             {  
                Console.WriteLine(a);  
                }  
              Console.Read();  
          }  
       }  
    }
    

    Output

     Total: 4
    
    One
    
    Two
    
    3
    
    4

    The example above shows the advantage of var when no predefined data types for variables are known. Firstly, we created one list and in turn assigned the data as One, Two, 3, and 4. Then use a foreach loop to browse the elements in the list, but this list is initialized with two types of values, hence it is difficult to browse the list. But if we use the var then everything becomes very easy, because no matter what the data type is, the program will automatically cast.

    What is Anonymous Types?

    Anonymous types allow you to create new types without defining them.This is an easy way to define read-only properties on a single object without explicitly defining the type. An anonymous type is a simple class generated by the compiler in IL (Intermediate Language) to store a set of values.Create an anonymous type with data type 'var' and the keyword 'new'. We have seen how the var data type works.Now let's see how anonymous types work with the "new" keyword.

    Implementing Anonymous Types

     using System;  
    using System.Text;  
    using System.Collections;  
    
    namespace DemoApplication1  
    {  
       class  __Anonymous1  
          {  
    
            static void Main(string[] args)  
                {    
    
                 var  emp = new {
                       Name = "Deepak", Address = "Noida", Salary=21000
                        };
                       Console.WriteLine("First Name : " + emp.Name);
                       Console.WriteLine("Local Address : " + emp.Address);
                       Console.WriteLine("salary : " + emp.Salary);
               
              Console.Read();  
           } 

    Output:

      First Name: Deepak
     Local Address: Noida
     salary: 21000
    
    In the above example, We can create anonymous types by using the “new” keyword together with the object initializer. As you can see from the above code example, the type is stored in a var and has three data items.For better understanding, the Anonymous types are an easy way to be useful when you need to create a simple object quickly and don't want to clutter your code with unnecessary classes.

    Implementing Nested Anonymous Type

     using System; 
     
    public class Employee_info { 
      
       // Main method 
        static public void Main() 
       { 
    
          // Creating and initializing nested anonymous object
    
     
           var emp_object = new {e_id = 11, s_name = "Pragya", profile = "C# Developer", 
                                   emp_ob = new { age = 27}}; 
    
           // Accessing the object properties 
    
    
           Console.WriteLine("Employee id: " + emp_object.e_id); 
           Console.WriteLine("Employee name: " + emp_object.s_name); 
           Console.WriteLine("Profile: " + emp_object.profile); 
           Console.WriteLine("age: " + emp_object.emp_ob.age); 
    
    } 
    
    

    Output

     Employee id: 11
    
    Employee name: Pragya
    
    Profile: C# Developer
    
    age: 27
    
    In C#, an anonymous type can also have another anonymous type as a property. Technically, The nested anonymous type is a great example of this equation. I took a very easy example, as shown above, emp_object is an anonymous type object that contains another anonymous type object called emp_ob this is nothing but a Nested Anonymous Type.

    Implementing Anonymous type in LINQ

     using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    
    class Employee { 
    
    	public int A_no; 
    	public string Aname; 
    	public string language; 
    	public int age; 
    } 
    
    class GFG { 
    
    	static void Main() 
    	{ 
    	List<Employee> g = new List<Employee> 
    	{ 
    
    		new Employee{ A_no = 22, Aname = "Mahesh", 
    					language = "C#", age = 23 }, 
    		new Employee{ A_no = 12, Aname = "Kunal", 
    					language = "Java", age = 20 }, 
    		new Employee{ A_no = 34, Aname = "Ayog", 
    					language = "Python", age = 22 }, 
    		new Employee{ A_no = 55, Aname = "Preeti", 
    					language = "CPP", age = 25 }, 
    
    		}; 
    
    
    	var emp_ob = from emp in g select new {emp.A_no, emp.Aname, emp.language}; 
    	foreach(var i in emp_ob) 
    		{ 
    			Console.WriteLine("Employee id = " + i.A_no + "\nEmployee name = "
    							+ i.Aname + "\nEmployee Language = " + i.language); 
    			Console.WriteLine(); 
    	} 
    	} 
    } 
    

    Output

      id = 22
    Employee name = Mahesh
    Employee Language = C#
    
    Employee id = 12
    Employee name = Kunal
    Employee Language = Java
    
    Employee id = 34
    Employee name = Ayog
    Employee Language = Python
    
    Employee id = 55
    Employee name = Preeti
    Employee Language = CPP
    
    
    LINQ query expressions mostly use anonymous types. Here Anonymous types are used with the "Select" clause of the LINQ query expression to return records. So that in a query we can contain properties that are not defined in the class. As shown in the above example, the Employee class contains four variables that are A_no, Aname, language, and age. But in the result, we only need A_no, Aname, and language, so we used a select query which creates a result of an anonymous type that only contains A_no, Aname, and language.

    Unlock the next level of C#

  • Summary

    In this article, I tried to explain var data type with examples and also anonymous type with a new keyword and their examples with different aspects. I hope after reading this article you will be able to use these tricks in your code. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article. Also don't forget to enroll in our .Net Training Course for a better understanding of .net concepts. Enjoy coding..!

    FAQs

    Q1. What are anonymous data types?

    An anonymous type is a type that has no name. Anonymous types allow you to encapsulate a set of read-only properties into a single unit. There is no need to define anonymous types in advance.

    Q2. What is an example of anonymous data?

    It is a data set from which personally identifying information, such as name, address, or telephone number, has been removed. This type of data can be used to analyze.

    Q3. What are C# anonymous types?

    Anonymous types allow you to create new types without defining them. This is an easy way to define read-only properties on a single object without explicitly defining the type. An anonymous type is a simple class generated by the compiler in IL (Intermediate Language) to store a set of values.

    Take our Csharp skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article

    Live Classes Schedule

    Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
    Azure DevOps Certification Training Course Jun 01 SAT, SUN
    Filling Fast
    10:00AM to 12:00PM (IST)
    Get Details
    Data Structures and Algorithms Training Jun 04 TUE, FRI
    Filling Fast
    08:30PM to 10:00PM (IST)
    Get Details
    ASP.NET Core Certification Training Jun 14 MON, WED, FRI
    Filling Fast
    07:00AM to 08:30AM (IST)
    Get Details
    ASP.NET Core (Project) Jun 22 SAT, SUN
    Filling Fast
    08:30PM to 10:30PM (IST)
    Get Details

    Can't find convenient schedule? Let us know

    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

    Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
    Accept cookies & close this