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?

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
Alex_P
  • 2,580
  • 3
  • 22
  • 37

1 Answers1

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;
}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • And in this case the constructor would take the dictionary as parameter - value input? – Alex_P Mar 29 '20 at 15:42
  • @Alex_P 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`. – RoadRunner Mar 29 '20 at 15:57
  • 1
    That's great. I did not think about a class. I will try it out! Thanks a lot. – Alex_P Mar 29 '20 at 16:03