Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcuts for overly terse generic types

Tags:

c#

.net

I'd like to pass a parameter of Dictionary to a method.

public static void Method(Dictionary<string, string> hash)

I'd really like to use the inline collection initializer

this is not legal

Method({{"Foo", "Bar"}, {"Bing", "Bong"}})

neither is this

Method(new {{"Foo", "Bar"}, {"Bing", "Bong"}})

this is

// outside the class    
using D = System.Collections.Generic.Dictionary<string, string>;
// calling with the type alias
Method(new D {{"Foo", "Bar"}, {"Bing", "Bong"}})

so is this

// once in a library somewhere
class SD : System.Collections.Generic.Dictionary<string, string> {}
// calling with the class
Method(new SD {{"Foo", "Bar"}, {"Bing", "Bong"}})

do you have a good shortcut like this I'm not aware of for solving my type collection initialization?

like image 974
JJS Avatar asked Dec 13 '25 02:12

JJS


1 Answers

No, you can't declare a dictionary the way you're wanting. In C#6, there is a slightly prettier Dictionary initializer syntax, but it's not exactly what you want:

using D = System.Collections.Generic.Dictionary<string, string>;

//...

Method(new D { ["Foo"] = "Bar", ["Bing"] = "Bong" });
like image 126
Jonesopolis Avatar answered Dec 14 '25 15:12

Jonesopolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!