Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference all instances of a generic class?

I've not completely wrapped my head around one aspect of Generics.

Let's say I have a Generic class:

public abstract SomeClass<T> where T : SomeInterface
{
    public bool DoSomethingsWithT(T theItem)
    {
        //doStuff!!!
    }

    public virtual bool IsActive
    {
       get { return true; }  
    }
}

So basicly I assume versions that inherit this class to be Active but I allow some of them to define their own.

Now later on I'm getting an object into a method that I know will be of the type SomeClass<T> but T could be any class implementing SomeInterface

public bool SomeMethod(object item)
{
    var something = item as SomeClass;

    return something.IsActive;
}

But this of course doesn't work as there is no class named SomeClass and I also can't do SomeClass<SomeInterface> as even if another class does inherit from this I'm unable to cast this.

How is this normally done? Should we create a class named SomeClass that SomeClass<SomeInterface> inherits from and in that class we define the IsActive property.

I'm seeing this same exact problem If I was gonna create a collection of items that inherit SomeClass<SomeInterface>.

like image 406
Ingó Vals Avatar asked Jan 19 '23 05:01

Ingó Vals


1 Answers

How about deriving from a class/implementing an interface that contains the common behaviour:

interface IIsActive
{
    bool IsActive{get;}
}
like image 105
spender Avatar answered Jan 29 '23 12:01

spender