Splatting in C#
Asked Answered
A

1

6

In PowerShell you can create a hashtable and add this hashtable to your function with an @, which is splatting in PowerShell.

$dict = @{param1 = 'test'; param2 = 12}
Get-Info @dict

Can one pass a dictionary as a collection of parameters to a constructor or method?

Ascham answered 29/3, 2020 at 15:23 Comment(3)
You can create Dictionary<TKey,TValue> instance and then pass it to a methodSibelle
@PavelAnikhouski, but they have to have the same type, right? In my example, there is one string and one integer. That would not be possible in C#, or?Ascham
@Ascham Dictionary can have different types e.g. Dictionary<string, int>Unto
P
3

If you want to support multiple type values in a dictionary, similar to your PowerShell Hash Table, you could create a Dictionary<string, object> here:

var dict1 = new Dictionary<string, object>
{
    {"param1", "test"},
    {"param2", 12},
}

Which could then be passed to a constructor:

private Dictionary<string, object> _dict;

public MyConstructor(Dictionary<string, object> dict)
{
    _dict = dict
}

The object type is just the System.Object class defined in .NET, which all types inherit from. You can check this in PowerShell with $dict.GetType().BaseType.FullName, which will give you System.Object.

However, using object as shown above is dangerous as it provides no type safety and requires you to cast to and from object. This is also known as Boxing and Unboxing. It would be better to use strong types here if you can, or rethink your design.

With the above in mind, we could use simple class here instead with strongly typed attributes:

public class MyClass {
    public string Param1 { get; set; }
    public int Param2 { get; set; }
}

Then you could just initialize it like this:

var myObject = new MyClass
{
    Param1 = "test1",
    Param2 = 12
};

And be passed to your constructor:

private MyClass _myObject;

public MyConstructor(MyClass myObject)
{
    _myObject = myObject;
}
Phlegmatic answered 29/3, 2020 at 15:39 Comment(3)
And in this case the constructor would take the dictionary as parameter - value input?Ascham
@Ascham Yes. I would probably go for the second option and just use a class. Then you can use strongly typed members and not have to worry about object.Phlegmatic
That's great. I did not think about a class. I will try it out! Thanks a lot.Ascham

© 2022 - 2024 — McMap. All rights reserved.