Passing null arguments to C# methods

前端 未结 7 2024
野的像风
野的像风 2020-12-14 06:46

Is there a way to pass null arguments to C# methods (something like null arguments in c++)?

For example:

Is it possible to translate the following c++ functi

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 07:01

    You can use 2 ways: int? or Nullable, both have the same behavior. You could to make a mix without problems but is better choice one to make code cleanest.

    Option 1 (With ?):

    private void Example(int? arg1, int? arg2)
        {
            if (arg1.HasValue)
            {
                //do something
            }
            if (arg1.HasValue)
            {
                //do something else
            }
        }
    

    Option 2 (With Nullable):

    private void Example(Nullable arg1, Nullable arg2)
        {
            if (arg1.HasValue)
            {
                //do something
            }
            if (arg1.HasValue)
            {
                //do something else
            }
        }
    

    From C#4.0 comes a new way to do the same with more flexibility, in this case the framework offers optional parameters with default values, of this way you can set a default value if the method is called without all parameters.

    Option 3 (With default values)

    private void Example(int arg1 = 0, int arg2 = 1)
        {
            //do something else
        }
    

提交回复
热议问题