Welcome to AspAdvice Sign in | Join | Help

Joydip Kanjilal's Technology Corner

Microsoft Most Valuable Professional (ASP.NET)

Tags

News

  • My book titled, "Sams Teach Yourself ASP.NET Ajax in 24 Hours" has been published!

    Received the MVP Award again!

    My first ever book has been published!


    I received the Microsoft MVP award in ASP.NET for 2007.

Articles

My articles at ASPNETPRO

My articles at ASPTODAY

My articles at CoderSource

My articles at DevX

My articles at DotNetJohn

My articles at www.asp.net

My articles at www.sql-server-performance.com

My Favorite blogs

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

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

Comments

Orcs Goblins and .NET said:

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

# January 4, 2008 4:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Enter the code you see below

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