C
C#2y ago
Hugh

✅ When calling a generic function, how can I tell it that I'm going to be passing null?

I've got a generic function which is something like this:
public ReturnType GetValue<ReturnType, ContentType>(ContentType content);
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);
string result = GetValue<string, NullType>(null);
Or even:
string result = GetValue<string, NullType>();
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);
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
2 Replies
ero
ero2y ago
you need to specify multiple overloads for that, i think. passing in null isn't exactly a good pattern (at least in my opinion) for that, i'd just have a second, empty overload
public TReturn GetValue<TContent, TReturn>(TContent? content);
public TReturn GetValue<TReturn>();
public TReturn GetValue<TContent, TReturn>(TContent? content);
public TReturn GetValue<TReturn>();
Hugh
HughOP2y ago
Thanks - that's really helpful - I didn't realise that I could do overloads like that
Want results from more Discord servers?
Add your server