Understanding the Dynamic Keyword in C# 4: Listing 1

DynamicString

public class DynamicString : DynamicObject {
  string str;

  public DynamicString(string str) {
    this.str = str;
  }

  public override bool TryInvokeMember(
    InvokeMemberBinder binder, object[] args, 
    out object result) {

    Console.WriteLine("Calling method: {0}", binder.Name);

    try {
      result = typeof(string).InvokeMember(
        binder.Name,
        BindingFlags.InvokeMethod |
        BindingFlags.Public |
        BindingFlags.Instance,
        null, str, args);
      return true;
    }
    catch {
      result = null;
      return false;
    }
  }
}

About the Author

Alexandra Rusina is a program manager on the Silverlight team. Prior to that she worked as a programming writer on the Visual Studio Languages team during the Visual Studio 2010 release. She also regularly blogged on the C# Frequently Asked Question blog.

comments powered by Disqus

Featured

Subscribe on YouTube