I have this generic function
private static T PostNew<T>() where T : IHttpModel, new()
{
var t = HttpModelsFactory.Create<T>();
var requestT = new RestRequest("/households", Method.POST);
requestT.AddParameter("application/json", t.ToJson(), ParameterType.RequestBody);
return t;
}
It needs to create and send an object of type T. This object, however, needs to have specific properties depending on what the type is.
class HttpModelsFactory
{
public static T Create<T>() where T : IHttpModel, new()
{
Type typeofT = typeof(T);
if (typeofT.Equals(typeof(Household)))
{
return CreateHousehold() as T;
}
}
public static Household CreateHousehold()
{
return new Household
{
Name = Randoms.RandomString()
};
}
}
This will have many more classes than just Household. However, it currently gives me this error: "The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint." How can I refactor the code to make it work or is there a better solution?