Search code examples
c#ienumerable

Initialize IEnumerable<int> as optional parameter


I have an optional parameter of type IEnumerable<int> in my C# method. Can I initialize it with anything but null, e.g. a fixed list of values?


Solution

  • No. You can only have compile time constants. You can assign in to null and then

    void SomeMethod(IEnumerable<int> list = null)
    {
        if(list == null)
            list = new List<int>{1,2,3};
    }
    

    Next code snippet is take from well-known C# in Depth book by Jon Skeet. Page 371. He suggest to use null as kind of not set indicator for parameters, that may have meaningful default values.

    static void AppendTimestamp(string filename,
                                string message,
                                Encoding encoding = null,
                                DateTime? timestamp = null)
    {
         Encoding realEncoding = encoding ?? Encoding.UTF8;
         DateTime realTimestamp = timestamp ?? DateTime.Now;
         using (TextWriter writer = new StreamWriter(filename, true, realEncoding))
         {
             writer.WriteLine("{0:s}: {1}", realTimestamp, message);
         }
    }
    

    Usage

    AppendTimestamp("utf8.txt", "First message");
    AppendTimestamp("ascii.txt", "ASCII", Encoding.ASCII);
    AppendTimestamp("utf8.txt", "Message in the future", null, new DateTime(2030, 1, 1));