0

I have the following expando object

 dynamic person = new ExpandoObject();
        person.FirstName = " FirstName ";
        person.SecondName = " FirstName ";
        person.FullName = person.FirstName + person.SecondName;
        person.BirthDate = new DateTime(1990, 1, 1);

        person.CalcAge = (Func<int>)
            (() => DateTime.Now.Year - person.BirthDate.Year);

I define CalcAge method to calculate age .. I want to add overloaded method that have a parameter like the below

person.CalcAge = (Func<DateTime, int>)
            ((DateTime date) => date.Year - person.BirthDate.Year);

How can I implement it with ExpandoObject in which I can do the below ?

int age1 = person.CalcAge();
MessageBox.Show(age1.ToString());

int age2 = person.CalcAge2(new DateTime(1980, 1, 1));
MessageBox.Show(age2.ToString());
Amr Badawy
  • 7,453
  • 12
  • 49
  • 84

1 Answers1

3

I don't believe you can. I'd strongly suggest you create a new named type instead. It looks like you know all the properties and methods you want to create - so just create a Person type. ExpandoObject is useful in some scenarios, but don't expect it to be able to cope with everything.

If you really want a dynamic object with this functionality, you'll need to derive a class from DynamicObject instead - that way you could implement overloading, if you wanted to (by intercepting method invocations).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Jon Skeet ! I know this is an old post by i hope you see this :-) are you maybe aware of a library that has something like ExpandoObject and allows overloaded methods? If I implement this myself how should i approach implementing the method resolution (Assuming i want to mimic C#'s behavior)? Thank you. – AK_ Feb 15 '15 at 23:54
  • 1
    @AK_: No, I don't know of anything, I'm afraid. Implementing the C# overloading rules would be *hard* - there's a lot of complicated stuff there. – Jon Skeet Feb 16 '15 at 06:48