C# conditional using and default parameter

One simple approach would be to just recurse if parameter is null:

string Foo(Resource parameter = null)
{
    if (parameter == null)
    {
        using (var res = new Resource())
        {
            return Foo(res);   
        }
    }
    else 
    {
        parameter.Something();
        ...
        return ...;
    }
}

You'll only recurse once, so you don't need to worry about unbounded stacks etc.


I would go with 2 separate methods. The one will contain all the logic - it will be clear and easy to maintain.

string Foo(Resource parameter)
{
     parameter.Something();
     /...../
     return /...../;
}

string Foo()
{
     using (var res = new Resource)
     {
         return Foo(res);
     }
}

This case also useful if you want to use injected parameter for testing purpose only. Looking for usages of parameterless method will lead to actual implementation, the other one will lead you directly to test cases.


I'd go for a local function:

string Foo(Resource parameter = null)
{
    if (parameter != null)
    {
        return DoSomething(parameter);
    }

    using (var resource = new Resource())
    {
        return DoSomething(resource);
    }

    string DoSomething(Resource res)
    {
        res.Something();
        /...../
        return /...../
    }
}

(In C# 8, you can make that a static local function).

If parameter can only be null when it's not provided (i.e. someone would never call Foo(null)), then you can use good old method overloading:

string Foo(Resource resource)
{
    resource.Something();
    /...../
    return /...../
}

string Foo()
{
    using (var res = new Resource())
    {
        return Foo(res);
    }
}

Tags:

C#