Question

I'm writing a cmdlet in C#. I have a number of things I need to initialize in order for my cmdlet to work properly.

Do I initialize by overriding BeginProcessing or in the default class constructor?

Stripped down example:

[Cmdlet(VerbsCommon.Set, "MyNoun")]
class MyCmdlet : PSCmdlet
{
    string s;

    [Parameter(Position = 0, Mandatory = true)]
    public string whatever;

    public MyCmdlet() 
    {
        //initialize s here?
    }

    public override void BeginProcessing()
    {
        //or initialize s here?
    }

}
Was it helpful?

Solution

That depends; does your initialization require the cmdlet's parameter's to be initialized? If you're just doing something like assigning string.Empty or an all-around default value, you can do it in the constructor. But if you were to do something like

this.s = "Value: " + this.whatever;

you would need to do it in BeginProcessing, as at that the time in the lifecycle, you're guaranteed to have the parameters bound to the cmdlet's members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top