Restrict Extension Methods

Sometimes you don’t want any object to get your generic extension method (like the DeepClone method desribed in this post). You can restrict the method by using a base class as the generic type parameter for the extension method, but that will mean that your classes have to inhertit from that type – also your extension may be too generic to restrict it for a specific base class (we don’t have multi-inheritance in c#). One easy way to perform that job is to use an interface – if you don’t have one that matches your needs, you might use an empty interface just for this purpose:

[Serializable]
public class TestMe : MarshalByRefObject, IDeepClonable
{ ... // see deep clone post}

public interface IDeepClonable { }

public static class DeepCloner
{
    public static T DeepClone<T>(this T toClone)
        where T : IDeepClonable
    { ... // see deep clone post}
}

In this case the test class does inherit from MarshalByRefObject and implements the empty interface IDeepClonable (for whitch it does no additional thing) and this way is able to present the DeepClone-method.

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

Sylvio's Infobox

Aktuelle Themen rund um SQL Server, BI, Windows, ...

Meredith Lewis

Professional Digital Portfolio

Vittorio Bertocci

Just another WordPress.com weblog

ScottGu's Blog

Just another WordPress.com weblog

AJ's blog

Thoughts and informations I think worthwhile to share...

Outlawtrail - .NET Development

Architecture & Design

SDX eXperts Flurfunk

Just another WordPress.com weblog

%d bloggers like this: