1

I have 4 static helper methods I want to combine into one if possible. Each method is identical aside from the input parameter data type, and setting a value in the ReturnDto and the ReturnDto type. I'm fairly new to Generics but not even sure if this is doable in an efficient matter other than having 4 strongly typed methods.

private static ReturnDto<int> MethodName(int val)
private static ReturnDto<string> MethodName(string val)
private static ReturnDto<bool> MethodName(bool val)
private static ReturnDto<DateTime> MethodName(DateTime val)
{
    //do some stuff here...
    return new ReturnDto<DateTime> { Val = val, Val2 = val2, Val3 = val3 };
}
1
  • 1
    what are val2 and val3 in your example?
    – Chris
    Sep 28, 2017 at 16:22

1 Answer 1

6

Yes:

private static ReturnDto<T> MethodName<T>(T val)

If you substitute T (generic type parameter) with any specific type you will get the method you expect. Think of T as a placeholder for any type. If not any type is valid then you can constraint it to comply with certain rules; read this for more information.

Also worth noting, is that type inference allows you to call this method without actually having to state the generic type:

var returnDto = MethodName(1); //instead of MethodName<int>(1)

T is inferred through the type of val which is int; the compiler has enough information to figure out the type of T with you needing to explicitly state it.

2
  • 1
    You should also note that by providing a specific type as the parameter, you don't need to specify the generic type when calling it.
    – krillgar
    Sep 28, 2017 at 16:29
  • It's so funny to look back on this now. I was 100% green on generics and a colleague made it sound so much more complicated than it is. Had I taken 15 minutes to really look it up I would have not even posted this!
    – joby-flick
    May 28, 2021 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.