'C# IDymanicParameters for powershell cmdlet required in both Parent and Child Class

We can define dynamic parameters for Powershell commandlets by adding IDynamicParameters and implementing it's GetDynamicParameters() method that creates the dynamic params.

My use-case: I need to create param2 in Child due to a new requirement, without stopping the creation of param1 in GrandParent.

class GrandParent: IDynamicParameters {
   object GetDynamicParameters();  // creates param1
}

class Parent: GrandParent {
// doesn't require dynamic params
}

class Child: Parent, IDynamicParameters
{
   object GetDynamicParameters(); // creates param2
}

But I get error CS0108: Child.GetDynamicParameters() hides inherited GrandParent.GetDynamicParameters(). Use the new keyword if hiding was intended.

Is there a good way to do this?



Solution 1:[1]

You could create a virtual non-public implementation you can override instead:

class GrandParent: IDynamicParameters
{
    protected virtual object GetDynamicParametersImpl()
    {
        // return dynamic params for grand parent from here
    }

    // no need to change this anywhere else
    public object GetDynamicParameters()
        => GetDynamicParametersImpl();
}

class Parent : GrandParent
{
    protected override object GetDynamicParametersImpl()
    {
        return null;
    }
}

class Child: Parent, IDynamicParameters
{
    protected override object GetDynamicParametersImpl()
    {
        // return dynamic params for child from here
    }
}

When Child.GetDynamicParameters() is invoked, the call to GetDynamicParametersImpl will dispatch the child-specific version

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen