Passing null arguments to C# methods

前端 未结 7 2005
野的像风
野的像风 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条回答
  •  Happy的楠姐
    2020-12-14 07:19

    The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace consolePlay
    {
        class Program
        {
            static void Main(string[] args)
            {
                Program.test(new DateTime());
                Program.test(null);
                //Program.test(); // <<< Error.  
                // "No overload for method 'test' takes 0 arguments"  
                // So don't mistake nullable to be optional.
    
                Console.WriteLine("Done.  Return to quit");
                Console.Read();
            }
    
            static public void test(DateTime? dteIn)
            {
                Console.WriteLine("#" + dteIn.ToString() + "#");
            }
        }
    }
    

    output:

    #1/1/0001 12:00:00 AM#
    ##
    Done.  Return to quit
    

提交回复
热议问题