DaImTo DaImTo - 2 months ago 16
C# Question

Return generic object type

The full code for this us up on GitHub Gist I am only including the portion I think is needed to show the problem.

Execute method:

public object Execute()
{
var request = createWebRequest();
request.Method = this.Method;
applyPostData(ref request);

request.ContentType = "application/json";
request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)";

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

try
{
return JsonConvert.DeserializeObject(responseString);
}
catch (Exception)
{
return new HttpResponse { message = responseString };
}
}


Ok this works kind of. However what I would like to be able to do is after the method is called cast it as the appropriate object type.

var response = (MetaDataResponse)request.Execute();


I know there should be some way possibly using generics (Wild guess) for me to json DeserializeObject the response and return it?

I ended up changing the return type of execute method to a string, and doing this.

public class MetaDataRequest : HttpRequestBase
{
public MetaDataResponse MetaDataItems { get; private set; }

public MetaDataRequest() : base(new Uri("https://www.googleapis.com/analytics/v3/metadata/ga/columns"), "GET")
{
this.addParameter("key", "xxxx");
var response = this.Execute();

try
{
MetaDataItems = JsonConvert.DeserializeObject<MetaDataResponse>(response);
}
catch (Exception)
{
var resultsx = new HttpResponse { message = response };
}
}
}


Which works but seams messy to me. Note this project is .Net framework 3.5 and I cant change that. Feel free to add any other tags you can think of.

Answer

Use generic with class MetaDataRequest

class MetadataRequest<T>:HttpRequestBase
{
    public T Execute()
    {
        var request = createWebRequest();
        request.Method = this.Method;
        applyPostData(ref request);

        request.ContentType = "application/json";
        request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)";

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return JsonConvert.DeserializeObject<T>(responseString);
    }
}

Then, to get the object, you can call the method like so:

MetadataResponse responseObject = (new MetadataRequest<MetadataResponse>()).Execute();

In this case, you can catch the exception thrown by .Execute() as it can only return null or an instance of type T.

Edit: you can also use generic method by following Jeremy Holovacs' answer.

Comments