[C#.NET] Inheritance - can i do this?

Soldato
Joined
12 Jun 2005
Posts
5,361
Hi there,

I know what inheritance is, I just don't really know when to apply it and how to use it properly, but I am pretty sure I should be using it for my current project, I just don't know how to go about doing it.

In Sudo code here is what my main class does (it does more stuff - but heres the important bit):

Code:
On Class Load -> Create [Class A] or [Class B]

Class A and Class B have the same public variables/events/methods, but have different logic for how they are raised/what they do and have different private variables/methods

Is there something I can do so that when either Class A or Class B are created (only one is used at one time), they are assigned to a variable/reference and i can use that variable to call the methods regardless of which class is referenced, because at the moment, for ever method i have in my main class, I have to do an if statement to check which class is created.

Hope this makes sense.

Thanks.
 
Last edited:
So you are saying each class has the same public interface (same method/property names and signatures)? If so you have 2 options:
1) If some of their methods and properties are identical, then have a 3rd (abstract) class that implements the identical methods and have the methods which arent identical abstract. If you do: baseClass someVariable = new classA(); you can use the object with a base class reference.

2) If nothing is identical in either of the classes, have them both implement an interface, which is basically a contract saying what public facing members the class must have. You can then reference them like so: ISomeInterface someVariable = new classA();

You can just have an if statement to decide which class to create and as long as they both inherit off the same object, you can have other methods which take a type of the inherited object (interface or abstract class) and invoke the correct methods. I'm really rubbish with techy terms but I think this is classed as Polymorphism.
 
I'm pretty sure I have to do the second thing on your list.

Heres an example of what I am currently doing:

Note that I have two variables to reference the two different classes and when I need to check which class is being used, I just check if refA == null and if so, then I use the refB variable. What I want, is just 1 variable to reference both classes.

Code:
public class MasterClass
{
   ClassA refA;
   ClassB refB;

   public MasterClass(int WhichClass)
   {
      if (WhichClass > 0)
      {
         refA = new ClassA();
      }
      else
      {
         refB = new ClassB();
      }
   }
}


public class ClassA
{
   public ClassA(Control ctrl)
   {
      //...logic...
   }

   public void Method1(string someStr)
   {
      //...logic...
   }

   private void SomeOtherMethod(int Number)
   {
      //...logic...
   }
}

public class ClassB
{
   public ClassB(Control ctrl)
   {
      //...logic...
   }

   public void Method1(string someStr)
   {
      //...logic...
   }

   private void AnotherMethod()
   {
      //...logic...
   }
}

EDIT:

Now definitely think its an interface I need, thanks (did some googling)





EDIT AGAIN:

But its also got me thinking, although it might make the code a bit messy, it might be best to put them in one big class rather than two?
 
Last edited:
Think very careful about your class structure - I don't see how you can jump from 2 classes to one... there was obviously enough differences in the first place. As Haircut has said, a factory might be the right idea, but either way - both will need to inherit from an interface (or abstract class, depending on whether you have any code repetition).

It sounds like you are very new to coding AND C# - so get your class structure down on paper before coding it, else you are going to have to recode it many times.
 
Think very careful about your class structure - I don't see how you can jump from 2 classes to one... there was obviously enough differences in the first place. As Haircut has said, a factory might be the right idea, but either way - both will need to inherit from an interface (or abstract class, depending on whether you have any code repetition).

It sounds like you are very new to coding AND C# - so get your class structure down on paper before coding it, else you are going to have to recode it many times.

I have thought about the structure, it could make sense in one large class which is overloaded (think thats the right term) to choose the type of class it is, but two me, it makes sense to have them in two difference classes as they are two separate entities. I think the interface is the best way to go about this.

lol....I wouldn't say I was new to coding or c#, but the way i have learnt it (self-taught) is in totally the wrong order tbh. I am at the point where i would need to right the structure of a class of this size as i can see it in my head........but i've always tried to accomplish things with the knowledge i already have, rather than the correct, most efficient way of doing it.

Thanks for your help guys.


EDIT:

When i have actually finished what I am doing, I will post up the project for people to have a look and critique.
 
Last edited:
What you're describing is a simple factory.
http://www.devcity.net/Articles/11/1/20011115.aspx

You don't need to have two variables at all, just declare a single variable as your interface and assign it to the class created by the factory.

EDIT. PS, it's pseudo code :p

Where does a factory come into it? He hasn't mentioned anything about how the client code should obtain instances of the classes, which is what the factory pattern deals with, he's just asking how he can access common members without knowing the object's true type.

OP; you probably want something like this:

Code:
interface Base
{
    void Foo();
    
    void Bar(string baz);
}

class A : Base
{
    public Foo()
    {
        Console.WriteLine("Class A says: foo");
    }
    
    public Bar()
    {
        Console.WriteLine("Class A says: " + baz);
    }
}

class B : Base
{
    public Foo()
    {
        Console.WriteLine("Class B says: foo");
    }
    
    public Bar()
    {
        Console.WriteLine("Class B says: " + baz);
    }
}

static class Program
{
    static void Main()
    {
        Base instance = new A();
        instance.Foo();
        instance.Bar();
        
        instance = new B();
        instance.Foo();
        instance.Bar();
    }
}
 
Last edited:
Ok - confused now.

I have done it via an interface, but with the interface I can't have fields which is annoying as it means i can't have eventhandlers.

------

So should i be using this Factory Pattern thing? - because, from what i gather from the link, it sure as hell doesn't look like what i want as it looks like its just extracting the common methods to another class. In my project, the method names are the same and they have the same parameters/return the same things, but the logic in them is different.
 
Last edited:
You would basically use it like this:

Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{

    interface IDoStuff
    {

        void DoThingA(string param1, string param2);

        string DoThingB(int param1);

    }


    class ClassA : IDoStuff
    {

        #region IDoStuff Members

        void IDoStuff.DoThingA(string param1, string param2)
        {
            // Concrete DoThingA
        }

        string IDoStuff.DoThingB(int param1)
        {
            // Concrete DoThingB
            return string.Empty;
        }

        #endregion
    }


    class ClassB : IDoStuff
    {

        #region IDoStuff Members

        void IDoStuff.DoThingA(string param1, string param2)
        {
            // Concrete DoThingA
        }

        string IDoStuff.DoThingB(int param1)
        {
            // Concrete DoThingB
            return string.Empty;
        }

        #endregion
    }

    class DoStuffSimpleFactory
    {

        public IDoStuff GetClass(string param1)
        {
            IDoStuff classToReturn = null;

            if (param1 == "A")
            {
                classToReturn = new ClassA();
            }
            else if (param1 == "B")
            {
                classToReturn = new ClassB();
            }

            return classToReturn;
        }

    }

    class Program
    {

        public static void Main(string[] args)
        {
            DoStuffSimpleFactory factory = new DoStuffSimpleFactory();

            IDoStuff classVariable = factory.GetClass("A");
        }

    }
}

If this is the sort of thing you need I would suggest a simple factory.
It might also be worthwhile reading up on the factory method and abstract factory design patterns for reference.
They are effectively more advanced versions of this.

You can do the same thing with an abstract class instead of an interface if you want to do this too.
 
Well from what i can see there, the factory is essentially useless as I can do that in a simple switch statement? The example in the link shows what the factory might be more worth while for, but for my project I don't think i need this:

Code:
IDoStuff classVariable = factory.GetClass("A");

as I could just have the "GetClass" logic in the same place where you assign to "classVariable"





-----------------------

EDIT: Been reading up on abstract classes and it looks like that might provide the solution i need as I can have EventHandlers in it.
 
Last edited:
Well from what i can see there, the factory is essentially useless as I can do that in a simple switch statement?

That's the point though - if you had a switch statement in the client it introduces a dependency on the explicit concrete classes, ClassA and ClassB.

With the factory you only have a dependency on the interface and not the implementation.
If you need to introduce a ClassC at some point you will need to modify you client rather than simply having the factory encapsulate the logic of creating the concrete class and leaving it up to that object.

If you're 100% sure you will only ever have the two classes then by all means don't have the factory, but it's a good design principle to be aware of.
 
Well from what i can see there, the factory is essentially useless as I can do that in a simple switch statement? The example in the link shows what the factory might be more worth while for, but for my project I don't think i need this:

Code:
IDoStuff classVariable = factory.GetClass("A");

as I could just have the "GetClass" logic in the same place where you assign to "classVariable"

The point is that it abstracts out of the client code the process of determining which class to instantiate. It's irrelevant that in this case the client code could have done it.

The client code (the IDoStuff classVariable = … bit) doesn't (and shouldn't) care which class it gets; it just wants one that implements IDoStuff. The factory method works out which class to instantiate and return (usually based on some runtime parameters, as in Haircut's example).

If you're 100% sure you will only ever have the two classes then by all means don't have the factory, but it's a good design principle to be aware of.

Even if he is sure of this, the factory would still be useful in that it would avoid repetition of the instantiation routine in the client code.
 
Last edited:
Right ok, there is a lot of terminology there which i don't particularly understand, but I am going to have a stab at explaining what it makes me think, just tell me if i'm wrong or right.

That's the point though - if you had a switch statement in the client it introduces a dependency on the explicit concrete classes, ClassA and ClassB.

Ok, is this something to do with the classes being public/private? And what do you mean by client? Remember all this code and the classes are in one user control.

With the factory you only have a dependency on the interface and not the implementation.
If you need to introduce a ClassC at some point you will need to modify you client rather than simply having the factory encapsulate the logic of creating the concrete class and leaving it up to that object.

Ok, what I think this means is, I won't have to edit any references to the factory, I will only have to edit the factory when i add classes. But surely this can be done with a simple function, rather than having to declare a factory?

If you're 100% sure you will only ever have the two classes then by all means don't have the factory, but it's a good design principle to be aware of.

No there might be more than two classes, but as said above, surely what is done with that factory instance can be done in a function?


----

By the way, I am sorry if it seems like i am challenging anyone, I know I am far inferior when it comes to this, I am just trying to understand it and really do appreciate all the help :)
 
Last edited:
Ok, is this something to do with the classes being public/private? And what do you mean by client? Remember all this code and the classes are in one user control.

Generally speaking, client code is a relative term that refers to the code that makes use of some set of functions, classes, etc. In this case the client code is the code that uses class A and class B.

The idea is that the client code should have as little knowledge as possible of the inner workings of the classes it uses, as this way if they change, then the it'll only affect the client code minimally.

Since your client code only needs to access the methods/events/properties that are common to class A and class B, it doesn't actually need to know about the classes at all. Instead, you can use an interface to specify the methods/events/properties that the client code needs to access so that it only has to deal with this interface.

Of course, if you're using an interface to hide the classes themselves from the client, then you need some kind of method that does know about these classes in order to actually instantiate them; this is where the factory comes in (and thus the factory is not considered part of the client code).

Ok, what I think this means is, I won't have to edit any references to the factory, I will only have to edit the factory when i add classes. But surely this can be done with a simple function, rather than having to declare a factory?

No there might be more than two classes, but as said above, surely what is done with that factory instance can be done in a function?

You're right actually; there's no need for that factory method to be an instance method. It may as well be made static (and doesn't necessarily need its own class; you could put it anywhere).

By the way, I am sorry if it seems like i am challenging anyone, I know I am far inferior when it comes to this, I am just trying to understand it and really do appreciate all the help :)

No problems – OOP can take a while to fully grasp :)
 
By the way, I am sorry if it seems like i am challenging anyone, I know I am far inferior when it comes to this, I am just trying to understand it and really do appreciate all the help :)

The best way to learn is to ask questions :)

If you're interested in learning more I can highly recommend this book:
http://www.amazon.co.uk/Head-First-Design-Patterns/dp/0596007124

It explains things in a way that keeps you interested, as well as giving real world type examples and explaining why things are best practices.

As Inquisitor says OOP takes a while to get, but practice makes perfect as they say!
I have no formal background in computer science (my degree was mathematical physics) and it took a while for all the concepts to sink in when I was learning all of this.
 
Whoop, high five! :cool:

Are you at Birmingham uni then?
I applied there, probably for the course you're doing now.
I was umming and ahhing between Nottingham and Birmingham as my first choice, but in the end the campus at Nottingham won me over though and I went there.

God, that was 10 years ago now :(
 
Back
Top Bottom