0

Given the following classes:

public class Person
{
    public string Name { get; set; }
}

public static class ExtenionPerson
{
    public static string GetPersonName(this Person person)
    {
        return person.Name;
    }
}

where a person has a name, and there is an extension method to get the person name. Now if I do:

dynamic person = new Person { Name = "Jon" };
var name = person.GetPersonName();

there will be thrown a RuntimeBinderException.

I know that extension methods should not be invoked on dynamic objects, but why is this now allowed? My guess is that because extension methods are resolved at compile-time and dynamic objects are resolved at runtime, as specified by the intelisense. How right is this?

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • You can use the static class call `ExtenionPerson.GetPersonName(person);` Do you really need to use dynamic here ? Or you're just writing this code as an example for this issue ? – Zein Makki Aug 14 '16 at 14:51
  • @user3185569 , I know this is how it can be invoked, but thank you for pointing this! – meJustAndrew Aug 14 '16 at 14:53
  • Who can explain that better than Eric Lippert: http://stackoverflow.com/a/5313149/3185569 – Zein Makki Aug 14 '16 at 14:53
  • @user3185569 I have read only the Jon's answer, didn't saw the second one. Thank you for flagging the question, I will close it myself :) – meJustAndrew Aug 14 '16 at 14:57

0 Answers0