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

  • New Visual Studio Razor Editor 'Close to Being Ready' for Blazor and Other Projects

    The experimental Razor editor for Visual Studio introduced last summer has been updated and is "close to being ready for normal daily development."

  • Microsoft Updates 'Must Have' Xamarin Community Toolkit

    The Xamarin Community Toolkit provides all kinds of effects, views and helpers to complement mobile app development with Microsoft's recently released, open source, cross-platform Xamarin.Forms 5.

  • JetBrains Unveils Plans for WinForms, WPF and More in Rider .NET IDE

    JetBrains announced plans for Windows Forms, Windows Presentation Foundation (WPF), ASP.NET and more tooling in the next release of its popular Rider IDE for .NET development.

  • Multi-Class Classification Using PyTorch: Model Accuracy

    Dr. James McCaffrey of Microsoft Research continues his four-part series on multi-class classification, designed to predict a value that can be one of three or more possible discrete values, by explaining model accuracy.

Upcoming Events