Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize IEnumerable<int> as optional parameter

Tags:

c#

ienumerable

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?

like image 798
J Fabian Meier Avatar asked Jan 10 '13 09:01

J Fabian Meier


People also ask

What is IEnumerable<>?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

What is IEnumerable string C#?

What is IEnumerable in C#? IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.


2 Answers

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));
like image 107
Ilya Ivanov Avatar answered Sep 22 '22 21:09

Ilya Ivanov


No - default parameters must be compile-time constants.

Your best bet is to overload the method. Alternatively, set the default value to null and inside your method detect a null and turn it into the list you want.

like image 35
Matthew Watson Avatar answered Sep 22 '22 21:09

Matthew Watson