Duck Typing

Duck Typing is a very nice mechanism and Guenter Prossliner’s article does it justice by introducing it to .NET with NDuck.

Duck Typing is a way to create a strongly typed wrapper at runtime that would take a type and ‘force it’ to implement an interface, instead of looking for the contract dynamically:

Before:

public static void SetImage(object owner, string resourceName){ PropertyInfo piImage = owner.GetType().GetProperty("Image"); EventInfo eiDisposed = owner.GetType().GetEvent("Disposed"); if (piImage == null || piDisposed == null) throw new ArgumentException("The 'owner' object" + " is not compatible with the required interface!"); Stream imgStream = typeof(ImageTools).Assembly.GetManifestResourceStream(resourceName); Image image = Image.FromStream(imgStream); piImage.SetValue(owner, image, new object[0]); EventHandler disposedHandler = delegate(object sender, EventArgs e){ image.Dispose(); imgStream.Dispose(); }; eiDisposed.AddEventHandler(owner, disposedHandler); } // Calling code ImageTools.SetImage(this.PictureBox1, "Image"); ImageTools.SetImage(this.Label1, "Image2");

After:

public interface IImageContainer{ Image Image{set;} event EventHander Disposed; } public static class ImageTools { public static void SetImage(IImageContainer obj, string resourceName){ Stream imgStream = typeof(ImageTools).Assembly.GetManifestResourceStream(resourceName); Image image = Image.FromStream(imgStream); obj.Image = image; // ensure that the Image and the Stream will // be closed when the PictureBox is diposed. obj.Disposed += delegate(object sender, EventArgs e){ image.Dispose(); imgStream.Dispose(); }; } } // Calling code ImageTools.SetImage( DuckTyping.Implement<IImageContainer>(this.PictureBox1), "Image"); ImageTools.SetImage( DuckTyping.Implement<IImageContainer>(this.Label1), "Image2");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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