Accessing properties of an anonymous types in C#?
anonymous-types, c#
Solution
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();
Problem
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.