I do not want to implement all the interface methods

It can be possible by ISP (Interface segregation principle). 

Let’s say we have a simple interface called as “IDal”.

public interface IDal

{

void Insert();

void Update();

}

Let’s assume that this interface is implemented by a class called as “SQL” as shown in the below code snippet. Now in this “SQL” class we would like to implement “Insert” method but we are not interested in the “Update” method. So the .NET interview question is “How can we implement the interface and not implement some methods of that interface,  as well as ensure that the program compiles properly ?”.

public class SQL : IDal

{

publicvoid Insert()

{

SqlConnection obj = newSqlConnection();

// Code for database insert goes here

}

publicvoid Update()

{

// Kept purposely empty

// as we do not want to implement

// the same.
thrownewNotImplementedException();

}

}
Above is  dirty way i.e. to leave the method empty or throw an exception not implemented as shown in the above code snippet.

The proper way is to apply ISP (Interface segregation principle).  In other words  create two  interfaces one which has only “Insert” method and the other which has “Insert” + “Update” as shown in the below code snippet.

publicinterfaceIDalInsert

{

void Insert();

}

publicinterfaceIDal : IDalInsert

{

void Update();

}

 

Now you can see the “SQL” class has just implemented “IDalInsert” interface and we just implement the “Insert” method – Clean right…

public class SQL : IDalInsert

{

publicvoid Insert()

{

SqlConnection obj = newSqlConnection();

// Code for database insert goes here

}

}

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