Job Lot

How can I restrict string values being passed into my method to ˇ°Openˇ±, ˇ°Closeˇ±, ˇ°Highˇ± and ˇ°Lowˇ±

Thanks




Re: Visual C# General Restricting parameter values?

Mattias Sjogren

The easiest way is probably to define an enum type with those values, and validate in the method that one of the defined enum values was passed in.






Re: Visual C# General Restricting parameter values?

Job Lot

But aren't enum integer based I want to validate string values.






Re: Visual C# General Restricting parameter values?

Sakthi Kumaran

use .ToString() method to get the string from Enum datatype.

U can't use spaces in between the string in this case.


U can also throw the exception for restricting.




Re: Visual C# General Restricting parameter values?

Job Lot

I have string with spaces in it.






Re: Visual C# General Restricting parameter values?

~rabin

In my opinion you have two ways to handle this situation:
1) Define an enum as others have said earlier.
Code Block

enum Values
{

Open,
Close,
High,
Low,

}


In this way you don't have to enforce anything to user, just define a function like
Code Block

void MyFunction(Values value)
{

if (value == Values.Open)

//do something

string strValue = value.ToString() //this will give the value in string like "Open", "Close" etc.

}


and user cannot pass anything except the predefined values.

2) Check the values manually and throw exception
Code Block

void MyFunction(string value)
{
if(value != "Open" && value != "Close" && value != "High" && value != "Low")
{
throw new ArgumentException("Unknown value.", "value");
}
}


This will enforce user to pass only one of those values.
But I would prefer option 1 to 2.





Re: Visual C# General Restricting parameter values?

Zamial

Yep Enum.

You stated your options for teh string and there is no spaces Smile.

However if there is I guess for simplicity you could create a string array or list containing your values and use the Contains method no the list to check the entry is allowed.

Otherwise use an Enum