Splatting in C#

1.1k views Asked by At

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?

1

There are 1 answers

3
RoadRunner On BEST ANSWER

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;
}