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?
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 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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With