"Does C# support multiple inheritance?"

A question i always get from my freinds, specially java guys:-)
the answer is not yet (not in C# 3.0) but there are some ways to get around it
although c# doesnt support mulitple inheritance it does support muliple implementation. which means that in c# you can implement more than 1 interface.
let's try it out
lets say we want a class to have the functionalities of a vehicle, and this class will represent a 4 wheel vehicle lets name this class as myCar
what we have to do now is we have to create two interfaces called IVehicle and I4Wheel

interface Ivehicle
{
void test();
void vehicle();
}

interface I4wheel
{
void test();
void 4wheel();
}

now lets create myCar class and lets inherit from IVehicle and I4Wheel

public class myCar: IVehicle,I4Wheel
{
//some code goes here;
}
 now if you you have noticed it there is a is a method with the same name in both interfaces. so how on earth myCar is going to defferentiate between the two??
simple 
just prefix it with the interface name (which is also known as explicit interface implementation)

public class myCar: IVehicle,I4Wheel
{
void IVehicle.test()
{
//implementation;
}
void I4Wheel.test()
{
//implementation;
}
}

 and "VOLLA" there you go, now c# supports multiple inheritance  :-)

0 comments:

Post a Comment