Alex
Alex

Reputation: 833

How to define a class property with type T

How can I have a property which can accept object of any type (of class)... something like this?

public class HttpConnectorRequest
{
    public int Id { get; set; }
    public T RequestObject { get; set; } where T: class
    public string ResponseData { get; set; }
    public Exception Exception { get; set; }
}

I am trying to acheive an alternative for something like this:

public class HttpConnectorRequest
{
    public int Id { get; set; }
    public ClassA ClassARequestObject { get; set; }
    public ClassB ClassBRequestObject { get; set; }
    public ClassC ClassCRequestObject { get; set; }
    public string ResponseData { get; set; }
    public Exception Exception { get; set; }
}

Upvotes: 15

Views: 25842

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499840

That's fine - you just need to make it generic:

public class HttpConnectorRequest<T> where T: class
{
    public int Id { get; set; }
    public T RequestObject { get; set; }
    public string ResponseData { get; set; }
    public Exception Exception { get; set; }
}

Then you'd write something like:

var request = new HttpConnectorRequest<string>();
request.RequestObject = "Hello!";

Generics is a big topic - MSDN is probably a reasonable starting point, although I suspect you'll want to read about it in a tutorial or book at some point. (While my own book, C# in Depth, obviously covers generics, plenty of others do too :)

Note that this makes the whole type generic. If you want to make just a single property generic, you're out of luck... although you could make a method generic:

public class HttpConnectorRequest
{
    // Other members elided

    public void SetRequestObject<T>(T value) where T : class
    {
        ...
    }

    public T GetRequestObject<T>() where T : class
    {
        ...
    }
}

Quite what this would do is up to you - bear in mind that someone could write:

var request = new HttpConnectorRequest();
request.SetRequestObject<string>("Hello");
var button = request.GetRequestObject<Button>();

Upvotes: 38

Related Questions