What is Anonymous Types?
Anonymous types provide a
convenient way to encapsulate a set of read-only properties into a single
object without having to explicitly define a type first. The type name is
generated by the compiler and is not available at the source code level. The
type of each property is inferred by the compiler.
The following example shows
an anonymous type that is initialized with two properties named EmployeeID and EmployeeName
an anonymous type that is initialized with two properties named EmployeeID and EmployeeName
namespace AnonymousType
{
public class Employee
{
#region
private Variable
private int
_employeeID;
private string
_employeeName;
#endregion
#region public
variable
public int EmployeeID
{
get
{
return _employeeID;
}
set
{
_employeeID = value;
}
}
public string
EmployeeName
{
get
{
return _employeeName;
}
set
{
_employeeName = value;
}
}
#endregion
public Employee()
{
}
public void Main()
{
Customer obj = new
Customer();
}
}
public class Customer
{
Employee obj = new
Employee { EmployeeID = 1, EmployeeName = "john" };
// employee
is Anonymous Type
var
employee = new Employee
{ EmployeeID = 1, EmployeeName = "john"
};
}
}
Anonymous types typically are used in the select clause of a query expression to return a subset of the
properties from each object in the source sequence.
public Customer()
{
List<Employee>
objEmployeeList = new List<Employee>
{
new Employee{EmployeeID=1,EmployeeName="john"},
new Employee{EmployeeID=2,EmployeeName="Raj"}
};
var employeeQuery = from
e in objEmployeeList select
new { ID = e.EmployeeID, Name
= e.EmployeeName };
foreach (var v in
employeeQuery)
{
Console.WriteLine("ID={0}, Name={1}", v.ID, v.Name);
}
}
No comments:
Post a Comment