Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Powershell [ValidateSet]

Tags:

c#

powershell

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
    }
}
like image 705
Naigel Avatar asked Oct 31 '22 03:10

Naigel


1 Answers

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!");
    }
}
like image 198
DavidG Avatar answered Nov 08 '22 03:11

DavidG