How can you use optional parameters in C#?

前端 未结 23 2573
逝去的感伤
逝去的感伤 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);
            }
    
        }
    }
    

提交回复
热议问题