(C# Language) Anonymous types and var Keyword

An anonymous type is described by a comma separated properties clubbed into curly braces. The properties are readonly. The corresponding data-type is generated by the compiler. The name of the data-type remains unknown. It is not accessible in source code. Such types are called anonymous types. They are used to quickly store data without the need of defining a data-type. They are also used in query expressions.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Example of an Anonymous Type

Let's write a small program to understand the syntax.

An anonymous type is created with the new keyword: var city = new {Name = , Height = }. The data-types of the properties Name and Height are inferred by the compiler on the basis of data stored in them.

The properties are read-only.

We can print the data in the usual way. The properties Name and Height are available on the object as if the data-type of the object were known in advance.

The intellisense, too, is available. You can verify it by typing the code yourself.


namespace ConsoleApp1
{
  class Program
  {
    static void Main()
    {
      var city = new { Name = "Sydney", Height = 45.8 };

      Console.WriteLine($"City = ({city.Name}, {city.Height}");

    }
  }
}

Notice that the concept of anonymous types has helped us keep the code simple and readable. We didn't have to create a class for the data. The class was anonymously created by the compiler. Anonymous types are class types.

Video Explanation (see it happen!)

Please watch the following youtube video:

Anonymous from a Subset of Properties

Anonymous types are most commonly generated from a subset of the properties of an object.

Consider a class consisting of three properties.

namespace ConsoleApp1
{
  class Point3D
  {
    public int X { get; set; }

    public int Y { get; set; }

    public int Z { get; set; }
  }

  class Program
  {
    static void Main()
    {
      Point3D point = new Point3D() {X = 4, Y = 2, Z = 1 };

      var tip = new { XPos = point.X, YPos = point.Y };

      Console.WriteLine($"Coord = ({tip.XPos}, {tip.YPos})");

    }
  }
}

Suppose we have an object of this class in the main function. Suppose also that we are interested in only two of the properties.

For this we can create an anonymous object. This object can be initialized only from the properties that we are interested in.

We can print the data using console writeline method.

Anonymous Types in select Clause of a Query

If you are familiar with SQL SELECT clause of database queries, then you already know that a few columns of a table can be extracted using a SELECT clause.

Anonymous types can be used to select a few properties from a LINQ (language integrated query). I present a simple example now.

Again consider a class that contains three properties. Inside main, we have a collection List to hold objects of this class. Next we add a few objects to this list.

Thus, the list contains two objects.

The query from p in points where p.Z < 2 select new { p.X, p.Y } is a LINQ query that can provide results by querying a collection as if it were a database. At this stage you will have to convince yourself that this query returns the columns X and Y of the records for which Z < 2.

The select clause uses an anonymous type to describe the columns. The names of the columns default to the names of the properties p.X and p.Y. We could have given our own names also as we have done in the previous examples.

Finally, a foreach loop runs on the query to print the matching records.


namespace ConsoleApp1
{
  class Point3D
  {
    public int X { get; set; }

    public int Y { get; set; }

    public int Z { get; set; }
  }

  class Program
  {
    static void Main()
    {

      List<Point3D> points = new List<Point3D>();

      points.Add(new Point3D() { X = 0, Y = 1, Z = 2 });

      points.Add(new Point3D() { X = 4, Y = 3, Z = 1 });

      var query = from p in points where p.Z < 2 select new { p.X, p.Y };

      foreach(var point in query)
      {
        Console.WriteLine($"point = ({point.X}, {point.Y})");
      }
    }
  }
}


This Blog Post/Article "(C# Language) Anonymous types and var Keyword" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.