Initialize IEnumerable <int> as an optional parameter
5 answers
Not. You only have compile time constants. You can assign null and then
void SomeMethod(IEnumerable<int> list = null) { if(list == null) list = new List<int>{1,2,3}; } The following code snippet comes from the famous book C# in Depth Jon Skeet . Page 371. He suggests using zero as a not set indicator for parameters that can 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); } } Using
AppendTimestamp("utf8.txt", "First message"); AppendTimestamp("ascii.txt", "ASCII", Encoding.ASCII); AppendTimestamp("utf8.txt", "Message in the future", null, new DateTime(2030, 1, 1)); +8