Search code examples
c#syntaxapi-design

Best practice to write a function or functions with generic type argument with default value of null


Say, I have a function with generic type argument with default value of null. For example, the signature of the function is

public T CallFunction<T,K>(K value = null) where K : class

So, when we call this function using the default value, it looks a bit weird.

string result = CallFunction<string, MyClass>()

The MyClass actually can be any class, since it is null. And we cannot skip it as string result = CallFunction<string>(). It will throw compiler error, specifically CS0305.

To avoid this weird situation, for example, my solution is adding a direct function of public T CallFunction<T>(). This results in code duplication. (For some reasons, I cannot add a private function for both). I wonder if we have a better API design?


Solution

  • There is no best practice for the case like that. However the best solution I see here is do something like this:

    public TResult CallFunction<TResult, TValue>(TValue value = null) where TValue : class
    {
        // your code here
    }
    
    public T CallFunction<T>() => CallFunction<T, object>();
    

    Then you could call just

    var result = CallFunction<string>();
    or 
    var result = CallFunction<string, {some type}>(value);
    

    Hope it helps