Home > Enterprise >  Is it possible to apply different types to a generic based on the polymorph?
Is it possible to apply different types to a generic based on the polymorph?

Time:10-03

I had a look at similar questions, but none seemed to getting at exactly what I was attempting, I'm not sure if this is related to covariance in generics which a read a little on in the .NET docs here.

Here is what I am trying to achieve, I have two families of classes, but an inherited queue that I want to handle a different type depending on the class its in, although a lot of the logic will be similar apart from 1 or 2 class specific things:

abstract class foo
{
     protected Queue<base> myQueue;
}

class bar:foo
{
    //something to allow me to use myQueue as a Queue<derived>
}

It's my first question on here, so sorry for any missing etiquette and thanks in advance!

CodePudding user response:

You can just add a generic type parameter and assign the derived class to it:

abstract class foo<T> where T: foo<T>
{
    protected Queue<T> myQueue;
}

class bar: foo<bar>
{
   
}

The where T: foo<T> makes sure that only the base class and all classes derived from it are allowed to be assigned

you could then also continue this pattern if you want to derive further from it:

class bar<T>: foo<T> where T: bar<T>
{
    
}

This makes sure that if you use your queue inside of that derived class, the type is at least bar<T>, with everything (methods, props..) available to it.

CodePudding user response:

I am not sure what it is exactly that you want to achieve, but this may help.

Seems like you want to make myQueue generic, you cant do that using this approach.

public abstract class Foo<T> where T : class
{
    protected Queue<T> myQueue;
}

public class Bar : Foo<SomeType>
{

}

public class SomeType
{

}

For example, code above has Bar class which inherits from Foo class, which has a generic parameter T. In this instance, SomeType is used for this generic parameter. Therefore class Bar has member myQueue of type Queue.

  •  Tags:  
  • c#
  • Related