How can you use optional parameters in C#?

前端 未结 23 2282
逝去的感伤
逝去的感伤 2020-11-22 17:02

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

We\'re building a web API tha

相关标签:
23条回答
  • 2020-11-22 17:31

    In the case when default values aren't available the way to add an optional parameter is to use .NET OptionalAttribute class - https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute?view=netframework-4.8

    Example of the code is below:

    namespace OptionalParameterWithOptionalAttribute
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Calling the helper method Hello only with required parameters
                Hello("Vardenis", "Pavardenis");
                //Calling the helper method Hello with required and optional parameters
                Hello("Vardenis", "Pavardenis", "Palanga");
            }
            public static void Hello(string firstName, string secondName, 
                [System.Runtime.InteropServices.OptionalAttribute] string  fromCity)
            {
                string result = firstName + " " + secondName;
                if (fromCity != null)
                {
                    result += " from " + fromCity;
                }
                Console.WriteLine("Hello " + result);
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:35

    For a larger number of optional parameters, a single parameter of Dictionary could be used with the ContainsKey method. I like this approach because it allows me to pass a List or a T individually without having to create a whole other method (nice if parameters are to be used as filters, for example).

    Example (new Dictionary<string,Object>() would be passed if no optional parameters are desired):

    public bool Method(string ParamA, Dictionary<string,Object> AddlParams) {
        if(ParamA == "Alpha" && (AddlParams.ContainsKey("foo") || AddlParams.ContainsKey("bar"))) {
            return true;
        } else {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:39

    A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

    [WebMethod]
    public string Foo(string arg1, XmlNode optarg2)
    {
        string arg2 = "";
        if (optarg2 != null)
        {
            arg2 = optarg2.Value;
        }
        ... etc
    }
    

    What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

    0 讨论(0)
  • 2020-11-22 17:39

    You can use default.

    public void OptionalParameters(int requerid, int optinal = default){}
    
    0 讨论(0)
  • 2020-11-22 17:41

    From this site:

    http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

    C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

    using System.Runtime.InteropServices;
    public void Foo(int a, int b, [Optional] int c)
    {
      ...
    }
    

    In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

    0 讨论(0)
  • 2020-11-22 17:41

    You could use method overloading...

    GetFooBar()
    GetFooBar(int a)
    GetFooBar(int a, int b)
    

    It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.

    You could use Nullable types...

    GetFooBar(int? a, int? b)
    

    You could then check, using a.HasValue, to see if a parameter has been set.

    Another option would be to use a 'params' parameter.

    GetFooBar(params object[] args)
    

    If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.

    0 讨论(0)
提交回复
热议问题