In Powershell when I define a function I can easily specify a list of possible values for a parameter using [ValidateSet]
, for example
function Log {
param (
[ValidateSet("File", "Database")]
[string]$Type = "File"
)
# my code
}
This way I define both a default value file
and a set of possible values file
and database
. Is there a similar way in C# or should I "manually" perform the check in the constructor?
public Log(string type = "file") {
public Log() {
if ... # here goes my check on the string
}
}
If you have only a finite range of values, then you could use an enumeration instead. First set up your enumeration:
public enum MyValues
{
File,
Database
}
And then use it as you would any other parameter type:
public void Log(MyValues type = MyValues.File)
{
switch (type)
{
case MyValues.File:
//Do file stuff here
break;
case MyValues.Database:
//Do database stuff here
break;
default:
throw new ArgumentException("You passed in a dodgy value!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With