Reputation: 1137
I am new to creating generic methods and have come across casting issues.
The following is a class library for communicating with an API. The object I am trying to cast to lives in my main application, which might be the issue but I do not know. What might I be doing wrong?
public T GetRequest<T>(Authentication auth, string api)
{
var restClient = new RestClient(Constants.Api.Client);
var restRequest = new RestRequest(api, Method.GET);
SetParameters(restRequest, auth);
var restResponse = restClient.Execute(restRequest);
return JsonConvert.DeserializeAnonymousType<T>(restResponse.Content, (T)new object());
}
Upvotes: 2
Views: 786
Reputation: 73482
In your method last line (T)new object()
is a problem. This makes no sense. You're creating new instance of System.Object
and trying to cast it to T
where T
could be anything. Your method is going to succeed only when called with generic parameter T
as System.Object
. For example GetRequest<object>(...)
will pass, otherwise it will fail.
Am not sure what you're trying to achieve here. If you can provide more info it will be easy to help.
Upvotes: 0
Reputation: 1500873
The object I am trying to cast to lives in my main application
It's not entirely clear what you mean by that, but the object you're trying to cast is just an instance of System.Object
:
(T)new object()
That can never work unless T
itself is object
.
The problem here appears to be that you're trying to use a method designed for working with anonymous types (so the second parameter is present as an "example" to make type inference work) - but with a type which isn't anonymous (T
).
I suspect you just want:
return JsonConvert.DeserializeObject<T>(restResponse.Content);
Upvotes: 2