Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Generic class as a Parameter to a non-generic class constructor [duplicate]

Assume the following code (Please read my question in the code comments in the final class):

//This is my Generic Class
public class ClientRequestInfo<K, V>
{
    public string Id { get; set; }
    private Dictionary<K, V> parameters;

    public ClientRequestInfo()
    {
        parameters = new Dictionary<K, V>();
    }

    public void Add(K key, V value)
    {
        parameters.Add(key, value);
    }
 }

public class ProcessParameters()
{
    private void CreateRequestAlpha()
    {
        ClientRequestInfo<int, string> info = new ClientRequestInfo<int, string>();
        info.Add(1, "Hello");
        SynchRequest s = new SynchRequest(info);
        s.Execute();
    }
    private void CreateRequestBeta()
    {
        ClientRequestInfo<int, bool> info = new ClientRequestInfo<int, bool>();
        info.Add(1, true);
        SynchRequest s = new SynchRequest(info);
        s.Execute();
    }
}

public class SynchRequest
{
    //What type should I put here?
    //I could declare the class as SynchRequest<K, V> but I don't want
    //To make this class generic.
    private ClientRequestInfo<????,?????> info;
    private SynchRequest(ClientRequestInfo<?????,?????> requestInfo)
    {
        //Is this possible?
        this.info = requestInfo;
    }

    public void Execute()
    {}
}
like image 535
Ioannis Avatar asked Sep 29 '09 17:09

Ioannis


People also ask

Can a generic method can be a member of an ordinary non-generic class?

Yes, There are two level where you can apply generic type . You can apply generic type on Method level as well as Class level (both are optional). As above example you applied generic type at method level so, you must apply generic on method return type and method name as well. You need to change a bit of code.

Can a non-generic class inherit a generic class?

Yes you can do it.

Can a generic class be a subclass of a non-generic class?

A generic class can extend a non-generic class.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.


1 Answers

If you don't want to make SynchRequestInfo generic, can you make a non-generic base class for ClientRequestInfo? --

public abstract class ClientRequestInfo
{
    public abstract void NonGenericMethod();
}

public class ClientRequestInfo<K, V> : ClientRequestInfo
{
    public override void NonGenericMethod()
    {
        // generic-specific implementation
    }
}

Then:

public class SynchRequest
{
    private ClientRequestInfo info;

    private SynchRequest(ClientRequestInfo requestInfo)
    {
        this.info = requestInfo;
    }

    public void Execute()
    {
        // ADDED: for example
        info.NonGenericMethod();
    }
}
like image 184
Ben M Avatar answered Sep 30 '22 21:09

Ben M