Check inside method whether some optional argument was passed

前端 未结 10 1562
眼角桃花
眼角桃花 2020-11-30 14:00

How do I check if an optional argument was passed to a method?

public void ExampleMethod(int required, string optionalstr = \"default string\",
    int optio         


        
10条回答
  •  失恋的感觉
    2020-11-30 14:38

    You can't, so you need to find a different way to check for the "optional" parameter. You can pass in a null if the parameter isn't being used, and then check

    if (optionalstr != null)
    {
        // do something
    }
    

    You can also overload the method, having one taking the optional parameters and one that doesn't take the optional parameters. Also, you can make it so that the method without the optional parameters passes in nulls to one of the overloaded methods.

    public void ExampleMethod(int required)
    {
        ExampleMethod(required, null, 0);
    }
    
    public void ExampleMethod(int required, string optionalstr = "default string",
    int optionalint = 10)
    {
    
    }
    

提交回复
热议问题