.net - How to call a method with the C# collection initializer? -


case

this morning refactored logging method , needed change method's 'params' parameter in normal array. consequently, call method had change array parameter. i'd method call change less possible, since it's heavily used utility method.

i assumed should able use collection initializer call method, gave me compile-error. see second call in example below. third call fine too, results in error.

example

void main() {     // works.     object[] t1 = { 1, "a", 2d };     test(t1);      // not work. syntax error: invalid expression term '{'.     test({1, "a", 2d });      // not work. syntax error: no best type found implicitly-typed array.     test(new[] { 1, "a", 2d });      // works.     test(new object[] { 1, "a", 2d }); }  void test(object[] test) {     console.writeline(test); } 

question

  • is there way call test() without initializing array first?

the problem c# trying infer type of array. however, provided values of different types , c# cannot infer type. either ensures values of same type, or explicitly state type when initialize array

var first = new []{"string", "string2", "string3"}; var second = new object[]{0.0, 0, "string"}; 

once stop using params there no way back. forced initialize array.

alternative continue using params:

public void test([callermembername]string callermembername = null, params object[] test2){} 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -