FrenkyB
FrenkyB

Reputation: 7217

How to return instance of concrete class from method with generic return type

I have a method which is being called from my application. Method is implemented from Google.Apis.Util.Store.IDataStore. I would like to return token from that method, but I don't know how. Token is class type TokenResponse. How to return class TokenResponse from method like this?

public Task<T> GetAsync<T>(string key)
{
  //TokenResponse token = new TokenResponse();
  //token.RefreshToken = @"rere545454545";
  //return token; -- I would like to return this, but it throws error
  return Task.FromResult<T>(default); //that works, but not much help out of it
}

Update

Basically I would like to return my own token, which I already have in database. But trying to make a new instance like:

TokenResponse token = new TokenResponse() 

throws and error

cannot create an instance of the variable type TokenResponse because it does not have the new() constraint

Upvotes: 0

Views: 304

Answers (1)

Iliar Turdushev
Iliar Turdushev

Reputation: 5213

The simplest way to fix your problem is to use the next approach:

  public Task<T> GetAsync<T>(string key)
  {
     TokenResponse t = new TokenResponse();
     // ...
     return Task.FromResult((T) ((object) t));
  }

You should guarantee that the method GetAsync<T> will always be called with type parameter T = TokenResponse. Otherwise, this code will throw InvalidCastException.

Upvotes: 0

Related Questions