public static object GetObject(int x)
{
return new object { };
}
public static object GetObject(string x)
{
return new object { };
}
public static void ProcessObject<T>(T x) where T : int, string <= got error here:
{
object o = GetObject(x);
}
Got error “A type used as a constraint must be an interface, a non-sealed class or a type parameter.”
How can I rewrite the code to get it work without write ProcessObject(int x) and ProcessObject(string x) twice?
So what you have now (according to accepted answer and your comments) is:
I’d recommend making public
intandstringoverloads, but to prevent code duplication, internally call another method:This makes your
publicmethods’ input values clear:intandstringare the only acceptable types, while still not duplicating your actual logic (// do stuff with o).You might dislike that the two public
ProcessObjectmethods are duplicates of each other, (on the surface anyway; under the hood, they’re calling two differentGetObjectoverloads) but I think it’s the best option.