Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4.0 - Does calling a protected method on a dynamic object call TryInvokeMember()?

In C# 4.0, there is a new DynamicObject.

It provides a "magic method" TryInvokeMember() that gets called when trying to call a method that does not exist.

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvokemember%28VS.100%29.aspx

What I would like to know is if TryInvokeMember() gets called when trying to call a protected method from outside the defining class.

I am contrasting the behaviour with PHP, which does call its equivalent "magic method" __call() in this situation.

like image 771
Jamie Avatar asked Mar 04 '10 21:03

Jamie


People also ask

What is C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.

What is C in simple words?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Why is C known as a mother language?

The C is a programming Language, developed by Dennis Ritchie for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc. C programming is considered as the base for other programming languages, that is why it is known as mother language.


1 Answers

When you write a call that would invoke a method that is not accessible (using the standard C# access rules), then the inaccessible method won't be called and the runtime will call the TryInvokeMember (where you can handle the call in some other way). Here is an example, so that you can try it:

class Test : DynamicObject {
  public void Foo() {
    Console.WriteLine("Foo called");
  }
  protected void Bar() {
    Console.WriteLine("Bar called");
  }

  public override bool TryInvokeMember
      (InvokeMemberBinder binder, object[] args, out object result) {
    Console.WriteLine("Calling: " + binder.Name);
    return base.TryInvokeMember(binder, args, out result);
  }
}

Now, we can create an instance of the object and try calling some of its methods:

dynamic d = new Test();
d.Foo(); // this will call 'Foo' directly (without calling 'TryInvokeMember')
d.Bar(); // this will call 'TryInvokeMember' and then throw exception

So, if you call the base implementation of TryInvokeMember, the C# dynamic binder will fail when calling an inaccessible method, but you can define your own handling of the case in TryInvokeMember (by setting the result to some value and returning true).

like image 58
Tomas Petricek Avatar answered Sep 29 '22 23:09

Tomas Petricek