I’m just learning about generics and have a question regarding method return values.
Say, I want a generic method in the sense that the required generic part of the method signature is only the return value. The method will always take one string as it’s parameter but could return either a double or an int. Is this possible?
Effectively I want to take a string, parse the number contained within (which could be a double or an int) and then return that value.
Thanks.
You cannot return either a
doubleor anintfrom a generic method without it also returning any other type.I might, for example, have a
Fooclass and your generic parse method, without any constraint, will allow this call to be made:The best that you can do with numbers is constrain on your function by only allowing
struct(value-types) to be used.But this will allow all number types, plus any other value-type.
You can constrain by interface type, but there isn’t an
INumericinterface ondoubleorintso you’re kind of stuck.The only thing that you can do is throw an exception if the wrong type is passed in – which generally isn’t very satisfying.
Your best approach, in this case, is to abandon generics and use separately named methods.
But, of course, this won’t help you learn generics. Sorry.