Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing properties of an anonymous types in C#?

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.

like image 968
dpp Avatar asked Jul 19 '13 08:07

dpp


People also ask

Which of the following selects an anonymous type?

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.

How do you utilize the anonymous type especially in LINQ?

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.

What are anonymous data types?

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.


1 Answers

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();
like image 193
Stormenet Avatar answered Sep 28 '22 17:09

Stormenet