Powershell: Non-nullable parameter best practices

Created on 30 Jun 2020  路  3Comments  路  Source: PowerShell/PowerShell

I'm writing my first binary PowerShell module and have C# 8 with non-nullable reference type checking enabled. I have a cmdlet with a string parameter called Name. The parameter has the ValidateNotNull attribute for PS to check if Name is null and error out. The compiler outputs a warning about the uninitialized string.

What are the best practices for non-nullable parameters where PS does a null check?

Steps to reproduce

[Cmdlet(VerbsCommon.Find, "Thing")]
public sealed class FindThing : PSCmdlet
{

    [Parameter()]
    [ValidateNotNull]
    // PS does a null check and errors.
    // Compiler produces this warning:
    // Non-nullable property 'Name' is uninitialized. Consider declaring the property as nullable.
    public string Name { get; set; }

    protected override void ProcessRecord()
    {
        // do thing
    }
}
Issue-Question

All 3 comments

In that case you can do one of two things:

  1. Set a default value of string.Empty just to satisfy the compiler, or
  2. "Assure" the compiler that it should never be null, effectively. I believe the pattern looks something like this:
public string Name { get; set; } = null!;

The postfix exclamation point can be used to tell the compiler that "no, this won't ever actually be null!" pretty much / the default value will never be accessed and it will always have a value by the time it's needed.

Thanks @vexx32. I was trying to use the null-forgiving operator but put it in the wrong spot.

I still put it in the wrong place all the time, it's very confusing! 馃槀

Was this page helpful?
0 / 5 - 0 ratings