-1

I am confused a bit about creating instance of generic object. I belive, that it supposed to be casted(somehow). In my code I am calling a service generic method:

jockey = await _scrapDataService.ScrapSingleJockeyPlAsync<LoadedJockey>(id, jobType);

And in my service method I want to achieve this, but I am not sure how to do it:

public Task<T> ScrapGenericObject<T>(int id, string jobType)
        {
            var someObject = new T();
            return someObject;
        }
bakunet
  • 197
  • 1
  • 12

2 Answers2

1

You need the new constraint

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

public Task<T> ScrapGenericObject<T>(int id, string jobType) where T : new()
{
    var someObject = new T();
    return someObject;
}

If you need to pass in any constructors you will have to use a different approach Activator.CreateInstance

Creates an instance of the specified type using the constructor that best matches the specified parameters.

 return (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2 });
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

The compiler will only allow this if you have a generic type constraint that tells the compiler that your type has a public parameterless constructor.

You achieve this using the new() constraint:

public Task<T> ScrapGenericObject<T>(int id, string jobType) where T: new()

Then the compiler knows that whatever type you pass in can be constructed via new T().

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138