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?
[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
}
}
In that case you can do one of two things:
string.Empty just to satisfy the compiler, orpublic 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! 馃槀