Check inside method whether some optional argument was passed

前端 未结 10 1585
眼角桃花
眼角桃花 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:31

    you can not check directly but you can check it by default value. for example:

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

    or

    public void ExampleMethod(int required, string optionalstr = "default string",
        int? optionalint)
    {
    
        if (required.HasValue==false)
           return;
    }
    

    Approach 2:

    Also you can use override methods:

    public void ExampleMethod(int required, string optionalstr = "default string")
    {
         //When this method called, means optionalint was NOT passed
    }
    
    public void ExampleMethod(int required, string optionalstr = "default string",
        int optionalint)
    {
        //When this method called, means optionalint was passed
    }
    

提交回复
热议问题