C
Join ServerC#
help
✅ When calling a generic function, how can I tell it that I'm going to be passing null?
HHugh12/13/2022
I've got a generic function which is something like this:
I always want to call it with a ReturnType specified, but sometimes I want to pass in
How can I call this to say that I want to pass in null? Ideally, I'd like to be able to do something like this:
Or even:
This second one is possible if I pick any type as the second generic type and change the function definition to this
However, I don't like putting a valid type in there if that's not what I mean, as that will be confusing to future developers (including future myself)
Thanks
public ReturnType GetValue<ReturnType, ContentType>(ContentType content);
I always want to call it with a ReturnType specified, but sometimes I want to pass in
null
as the content.How can I call this to say that I want to pass in null? Ideally, I'd like to be able to do something like this:
string result = GetValue<string, NullType>(null);
Or even:
string result = GetValue<string, NullType>();
This second one is possible if I pick any type as the second generic type and change the function definition to this
public ReturnType GetValue<ReturnType, ContentType>(ContentType? content = null);
However, I don't like putting a valid type in there if that's not what I mean, as that will be confusing to future developers (including future myself)
Thanks
EEro12/13/2022
you need to specify multiple overloads for that, i think. passing in
null
isn't exactly a good pattern (at least in my opinion)EEro12/13/2022
for that, i'd just have a second, empty overload
EEro12/13/2022
public TReturn GetValue<TContent, TReturn>(TContent? content);
public TReturn GetValue<TReturn>();
HHugh12/13/2022
Thanks - that's really helpful - I didn't realise that I could do overloads like that