Welcome to AspAdvice Sign in | Join | Help

Put your interfaces to best use!

You can restrict creating instances of classes using C# in more ways than one. You can make the class abstract, static or even use a private constructor. But, what if you want to allow a method of a class to be invoked only using an interface reference, i.e., the interface that the class implements? Tricky, right?

Let me explain. Here is an interface called IBusinessEntity that the class BusinessEntity implements.

public interface IBusinessEntity

{

void Serialize();

}

It contains only one method called Serialize. Now, here is the BusinessEntity class.

public class BusinessEntity : IBusinessEntity

{

public void Serialize()

{

//Some code

}

}

Now, you can instantiate the BusinessEntity class and invoke the Serialize() method using any of following ways.

IBusinessEntity bE = new BusinessEntity();

bE.Serialize();

or

BusinessEntity bE = new BusinessEntity();

bE.Serialize();

What if you want to restrict to the former only? Simple, here is the modified BusinessEntity class.

public class BusinessEntity : IBusinessEntity

{

void IBusinessEntity.Serialize()

{

//Some code

}

}

Now, you can invoke the Serialize() method only using the statements shown below.

IBusinessEntity bE = new BusinessEntity();

bE.Serialize();

Check it out!

Thanks,

Joydip

Published Friday, January 04, 2008 5:24 PM by joydipkanjilal

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Explicitly and Implicitly Implementing Interfaces

Friday, January 04, 2008 4:26 PM by Orcs Goblins and .NET

I read an interesting blog post from Joydip Kanjilal where he described an interesting little trick with

# re: Put your interfaces to best use!

Wednesday, January 23, 2008 7:19 AM by Anonymous

# Explicitly and Implicitly Implementing Interfaces

Wednesday, May 06, 2009 2:19 PM by Brendan Enrick's Blog

I read an interesting blog post from Joydip Kanjilal where he described an interesting little trick with interfaces . I, being a bit of a fan of interfaces, read the post and thought I'd throw my $0.02 in also. I couldn't pass up an opportunity to talk

# Explicitly and Implicitly Implementing Interfaces

Tuesday, May 19, 2009 9:20 AM by Brendan Enrick's Blog

I read an interesting blog post from Joydip Kanjilal where he described an interesting little trick with interfaces . I, being a bit of a fan of interfaces, read the post and thought I'd throw my $0.02 in also. I couldn't pass up an opportunity to talk

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below