This is a simple c# OOP
interview question which was asked to one of our readers in an IT company.
Let us try to understand the question.
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();
}
}
Now there are two ways of doing this first is a dirty way
and second is the proper way ;-).
Now one important point we need to remember about interface
is that if we implement an interface we have to implement all the methods. So
there is really no escape that if you are implementing interface and you can get
away not implementing some methods.
So the dirty way is to leave the method empty or throw an
exception not implemented as shown in the above code snippet.
Keeping a method empty is definitely not a good practice as
developers can get confused when they call the method and nothing happens. So
in case you are forced to implement the interface method you can always raise
“NotImplementedException” error and let the consumer of your class know that
this method has no implementation.
That was a bad way, 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
}
}
So the way you will answer this .NET interview question is,
we can use ISP (Interface segregation principle) and divide the interface in to
two parts and then implement the necessary interface as needed. In case interviewer
does not agree then you can talk about the dirty method i.e. throwing a not
implemented exception.
You can watch our
16 .NET and c# interview questions and answer videos from
http://www.youtube.com/watch?v=JNwvVrK_y-I&playnext=1&list=PL5753E1DFB675A268
You can also read this most asked
.Net interview question on partial classes.