8

I'm designing a cmdlet using plain C#. Is it possible to define a default value for a parameter?

Script cmdlet:

[Parameter] [string] $ParameterName = "defaultValue"

Which is the equivalent for C#?

[Parameter]
public string ParameterName { get; set; }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fra
  • 3,488
  • 5
  • 38
  • 61

2 Answers2

9

Since C# 6.0 has been released:

[Parameter]
public string ParameterName { get; set; } = "defaultValue";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
isxaker
  • 8,446
  • 12
  • 60
  • 87
9

With auto-implemented properties, you can't. You will need to create the actual getter and setter.

Something like this:

private string _ParameterName = "defaultvalue";

[Parameter]
public string ParameterName 
{
     get
     {
          return _ParameterName ;
     }
     set
     {
         _ParameterName  = value;
     }
}
Matt
  • 45,022
  • 8
  • 78
  • 119
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
  • 1
    Thanks. Maybe it was too obvious... I could do it with auto-implemented too, just setting them in the constructor. – fra Feb 08 '11 at 08:47
  • yes sure why not...i answered in the context of the example you showed in question – Shekhar_Pro Feb 08 '11 at 08:48