How Can I Accept a Generic Class and Use Its Properties / Methods

Posted by Blake Blackwell on Stack Overflow See other posts from Stack Overflow or by Blake Blackwell
Published on 2010-06-09T20:50:47Z Indexed on 2010/06/09 21:02 UTC
Read the original article Hit count: 141

Filed under:
|

I want to create a class that could hold any of a number of same type of classes. For example lets says I have a base class like follows:

public class BaseClass
{
    public string MyBaseString
    {
         get;
         set;
     }
}

And then I have a few derived classes like this:

public class DerivedClass : BaseClass
{
     public MyDerivedClassString
     {
         get;
         set;
     }
}

public class DerivedClass2 : BaseClass
{
     public MyDerivedClass2String
     {
         get;
         set;
     }
}

Now I would like a class that accepts one of these implementations and does stuff with it. Here is the only thing I can think of, but there must be a better way:

public class ClassA
{
    public object MyClass
    {
        get;
        set;
    }

    public ClassA (object myClass)
    {
        MyClass = myClass;
        if (object is BaseClass)
        {
              //do something
        }
        else if (object is DerivedClass)
        {
             //do something specific to derived class
        }
        else if (object is DerivedClass2)
        { 
             //do something specific to derived class 2  
        }
    }
}

I'm not sure really what I'm looking for here. Any ideas would be great!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET