views:

78

answers:

4

Hi,

If I have a class:

public blah
{

}

Then I have another class that inherits blah"

public ablah : blah
{

}

Can I do this then?

public class Someservice
{
 public bool SomeBlah(blah b)
 {

 }   
}

Could I call it the service with either classes blah or ablah?

ie.

Someservice s1 = new Somesercie();

s1.SomeBlah(new blah());

s1.SomeBlah(new ablah());

I saw this somewhere, and I thought this was only possible if one used an Interface?

A: 

That would work just fine. (assuming that it would compile... check your spelling)

Matthew Whited
+1  A: 

It's called polymorphism and it's possible with classes as well as interfaces.

Generally you would use a class if you wanted to provide some of the implementation in the base class (which is not possible inside an interface declaration). Also interfaces only allow for public members..

Miky Dinescu
A: 

You can do this just fine. You're using standard inheritance, in this case. The best way to think of it is this: "ablah" is a "blah", so you can use an "ablah" instance anywhere that's expecting a blah.

A common example is a

public class Animal {} 
public class Dog  : Animal {}

In this case, "Dog" is an "Animal" (which you'd expect), so if you have a method that takes an animal, it will work with a Dog.

Reed Copsey
+1  A: 

Yep, although it is not using an interface but rather a facet of object oriented programming called Polymorphism (http://msdn.microsoft.com/en-us/library/ms173152(VS.80).aspx)

If you had

public class Someservice{ 
    public bool SomeBlah(ablah b) 
    { }  
}

Your SomeService code wouldn't work, because while you can cast an ablah object into a blah object, you cannot do the reverse. It's like saying I have a car (blah), and it's a Toyota (ablah). If I was doing something that needed a car, my Toyota would fit the requirement. But if I was going to do something that required a Toyota, I couldn't use any old car.

HTH. pk