Anonymous type provides an easy way to define objects. Anonymous type is introduced in c# 3.0.
Syntax:
var str = new { Id = 0, Name = "Sample", Bday = "05/03/2006" };
With the special purpose of providing an easy way to define objects with some read only properties.
C# introduced anonymous type to avoid defining classes for minimal use. You saw above example that we have added three read-only properties. Id, Name and Birthday with new keyword.
Notice here:
Anonymous type contains one or more public read-only properties. While an object of the class cannot assign value to read-only properties.
Let’s take an example of public ready only properties in “myClass”.
class myClass { public readonly int Id = 1; public readonly string Name; public readonly DateTime Bday; }
So in above example you can see we have added three read only properties and in id we have assign “1” value where in other two properties have not.
So default value of read-only properties will always have its default value.
Example: anonymous and class
using System; class Program { static void Main() { //anonymous type declaration var str = new { Id = 1, Name = "Sample Anonymous", Bday = Convert.ToDateTime("05/03/2006") }; Console.WriteLine("Anonymous--------------------------------"); Console.WriteLine("Id: {0}", str.Id); Console.WriteLine("Name: {0}", str.Name); Console.WriteLine("Bday: {0}", str.Bday); Console.WriteLine(""); //object of class myClass cls = new myClass(); Console.WriteLine("Class--------------------------------"); Console.WriteLine("Id: {0}", cls.Id); Console.WriteLine("Name: {0}", cls.Name); Console.WriteLine("Bday: {0}", cls.Bday); Console.WriteLine(""); } } class myClass { public readonly int Id = 1; public readonly string Name = "Sample Class"; public readonly DateTime Bday = Convert.ToDateTime("05/03/2006"); }
Output:
Anonymous--------------------------------
Id: 1
Name: Sample Anonymous
Bday: 5/3/2006 12:00:00 AM
Class--------------------------------
Id: 1
Name: Sample Class
Bday: 5/3/2006 12:00:00 AM
In above example you can see we have created anonymous type and added id, name and birthday. Same we have create class and added read-only properties with values.
So now you understood that if we want to define some value without create a class and object we can use anonymous type if use would be minimal.
you can also visit: www.mybook-lang.com
No comments:
Post a Comment