
-----------------------------------
rdrake
Sat Jun 27, 2009 12:09 am

[C#] Inheritance
-----------------------------------
So, you want to learn more about inheritance in C#?  Well, here we go...

Much like Java, in C# there is no multiple inheritance.  You can inherit from multiple interfaces but not classes.

Let's start off with a simple class and go from there.

public class Square extends Rectangle {
    public Square(float width) {
        super(width, width);
    }
}

Let's say you wanted to access the methods of a Square object.  Try this out:

Questions
Will these work?  Why or why not?

Problem 1:
Problem 2:
Problem 3:
Problem 4:
Answers
Problem 1:
Works just fine.  It should print out an answer of "25" if all went well.

Problem 2:
Have another look at the Shape class.  Does it contain a property called "Height"?  No, well that's why you got a compilation error.

The reason calling GetArea() worked in problem 1 is because Shape contained a definition for that method.  If you really want you can cast your object back to the subclass when calling properties and methods that only exist on a lower level like so:

Problem 3:
Uh oh, compilation error!  Mono is not pleased.

error CS0144: Cannot create an instance of the abstract class or interface `Shape'

Just like it says, the Shape class is marked as abstract.  Since it could contain methods that have not yet been implemented, we cannot create objects of that type.  Instead we must subclass the abstract class (forcing us to implement the abstract methods if our subclass is not also abstract), and create instances of that.

Problem 4:
Again it will not compile.  The code does not compile because Square is a subclass of Rectangle, not the other way around.  Square already knows all about Rectangle and what it contains, but Rectangle does not know everything (if anything) that's been added to Square.

You can do this:
[code]Square s = (Square)new Rectangle(5f, 6f);
Console.WriteLine(s.GetArea());[/code]

That code will compile, but it throws an exception for the same reason that I explained above -- doing the above does not make sense.  Ever.

Well, there you have it.  A very basic introduction to inheritance in C#.  Next up I'll discuss more features such as differences between public/private/protected in terms of instance variables and extension methods.

Edit:  Added code as an attachment.

-----------------------------------
wtd
Wed Jul 01, 2009 7:17 pm

RE:[C#] Inheritance
-----------------------------------
I see a quick mention of interfaces, but no code examples.

-----------------------------------
sjjoseph
Wed Jan 13, 2010 5:29 am

Re: [C#] Inheritance
-----------------------------------
Hello rdrake!!
Nice description about inheritance.
Good to see with example. It is helping in understanding. 
Thanks for this post.
