Say I created an anonymous type for person that has name and birth date as properties:
var person = new{ Name = "Mike", BirthDate = new DateTime(1990, 9, 2) };
then later on, decided to add a method that will return the age of the person.
var person = new { Name = "Mike",
BirthDate = new DateTime(1990, 9, 2),
GetAge = new Func<int>(() => { return /* What? */; }) };
How do I access the property BirthDate
so that I can compute the age? I tried using this
but of course it didn't work.
Mostly, anonymous types are created using the Select clause of a LINQ queries to return a subset of the properties from each object in the collection.
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class. As shown in the below example, the Geeks class contains four properties that are A_no, Aname, language, and age.
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
You can't. You will have to create a Person
class to have such functionality:
class Person {
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public TimeSpan Age {
get {
// calculate Age
}
}
}
var person = new Person {
Name = "Mike",
BirthDate = new DateTime(1990, 9, 2))
};
Edit: Another option is to create an extension method for DateTime
:
public static TimeSpan GetAge(this DateTime date) {
// calculate Age
}
var person = new {
Name = "Mike",
BirthDate = new DateTime(1990, 9, 2))
};
TimeSpan age = person.BirthDate.GetAge();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With