Posted by: leppie | February 2, 2011

Dynamic binding in C#

So someone asked a question on StackOverflow today, and I gathered the best solution was to use dynamic binding.

Here follows a simple example on how to achieve it:

class DynamicConsole : TextWriter
{
  readonly TextWriter orig;
  readonly TextWriter output;

  public DynamicConsole(string filename)
  {
     orig = Console.Out;
    output = File.AppendText(filename);
    Console.SetOut(output);
  }

  public override System.Text.Encoding Encoding
  {
    get { return output.Encoding; }
  }

  public override void Write(char value)
  {
    output.Write(value);
  }

  protected override void Dispose(bool disposing)
  {
    Console.SetOut(orig);
    output.Dispose();
  }
}

Usage:

Console.WriteLine("Real 1");

using (new DynamicConsole("Foo.txt"))
{
  Console.WriteLine("Moo");

  using (new DynamicConsole("Bar.txt"))
  {
    Console.WriteLine("Ork");
  }

  Console.WriteLine("Bar");
}

Console.WriteLine("Real 2");

When running you get the following:

This will print to the Console:

Real 1
Real 2

It will append to Foo.txt:

Moo
Bar

It will append to Bar.txt:

Ork

I will update the code later to make it generic, so any property, method or field can be used for the dynamic binding. Stay tuned!

Update:

Posted an article on CodeProject last Friday. This is a generic implementation: Dynamic binding in C#

About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: