Initialize IEnumerable <int> as an optional parameter

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

+6
source share
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
source

No - the default parameters must be compile time constants.

It’s best to overload the method. Alternatively, set the default value to null, and inside your method, define zero and include it in the list you want.

+4
source

How to make the default value equal to zero, but inside the method

 numbers = numbers ?? Enumerable.Empty<int>(); 

or

 numbers = numbers ?? new []{ 1, 2, 3}.AsEnumerable(); 
+4
source

No, you need a compile-time constant.

But you can use overloading as work:

 public void Foo(int arg1) { Foo(arg1, new[] { 1, 2, 3 }); } public void Foo(int arg1, IEnumerable<int> arg2) { // do something } 
+3
source

Well, since you need compile time constants, you need to set it to null

but then you can do the following in your method

  list = list ?? new List<int>(){1,2,3,4}; 
+3
source

All Articles