How to refer to all instances of a generic class?

I did not completely wrap my head around one aspect of Generics.

Say I have a general class:

public abstract SomeClass<T> where T : SomeInterface { public bool DoSomethingsWithT(T theItem) { //doStuff!!! } public virtual bool IsActive { get { return true; } } } 

So, I assume that the versions inheriting this class are active, but I allow some of them to define their own.

Now when I get the object in the method, which, as I know, will be of type SomeClass<T> , but T can be any class that implements SomeInterface

 public bool SomeMethod(object item) { var something = item as SomeClass; return something.IsActive; } 

But this, of course, does not work, because there is no class named SomeClass , and I also can not make SomeClass<SomeInterface> , since even if another class is inherited from it, I can not distinguish it.

How is this usually done? If we create a class called SomeClass that inherits SomeClass<SomeInterface> in this class, we define the IsActive property.

I see the exact same problem. If I was going to create a collection of elements inheriting SomeClass<SomeInterface> .

+4
source share
5 answers

Use the interface to implement in the universal class:

 interface ISomeClass { bool IsActive {get;} } public abstract SomeClass<T> : ISomeClass where T : SomeInterface { public bool DoSomethingsWithT(T theItem) { //doStuff!!! } public virtual bool IsActive { get { return true; } } } public bool SomeMethod(object item) { var something = item as ISomeClass; return something.IsActive; } 
+3
source

How about getting a class / implementation of an interface that contains common behavior:

 interface IIsActive { bool IsActive{get;} } 
+4
source

Should we create a class called SomeClass , which SomeClass<SomeInterface> inherits and in this class we define the IsActive property.

Yes, exactly what you should do (and how it's usually done).

Or you could follow spender recommendations and use an interface instead of an abstract class. This is probably better because it fulfills the same goal without limiting you to a rigid type hierarchy.

+2
source

Use the interface not to implement the class

 public bool SomeMehtod(object item) { return ((SomeInterface)item).IsActive; } 

I just realized that the IsActive property is not defined in the interface either.

Then the best way to do this is to determine if the class is SomeClass , and then return IsActive

 public bool SomeMethod(object item) { var something = item as SomeClass; if (something != null) { return something.IsActive; } else { return somethingElse; } } 
0
source

Not sure if everything worked out for me, but will this method signature work in SomeMethod?

  public bool SomeMethod(SomeClass<SomeInterface> item) { return item.IsActive; } 
0
source

All Articles