Predefined Parameters in a Function

looked, but not very lucky, I want to create a function that allows you to pass only certain elements as the first parameter.

eg. it should only allow the following lines:

"error", "warning", "info" 

then the call will be

 showme("error"); or showme("warning"); or showme("info"); 

Can this be done? I know that I can determine

 showme(string type){} 

but ideally I need showme(string type "error"){}

+4
source share
3 answers

I suggest enum

 public enum ErrorType { error, warning, info } public void ShowMe(ErrorType errorType) { switch (errorType) { case ErrorType.error: //do stuff break; case ErrorType.warning: //do stuff break; case ErrorType.info: //do stuff break; default: throw new ArgumentException("Invalid argument supplied"); break; } } //Invoke the method ShowMe(ErrorType.info); 
+4
source

According to Rozuur's comment, Enum is a clean option. Otherwise, you can try using code contracts: http://www.cauldwell.net/patrick/blog/CodeContracts.aspx

+3
source

You can combine the logic, which depends on your set of values, into a class with a private constructor and retrieve instances either through the singleton properties or through the factory method.

Sort of:

 public class StringConstraint { private StringConstraint() public static readonly StringConstraint error = new StringConstraint() ... public void DoStuffWithStringValue() { // Here you do the logic that depends on your particular string value // eg (always) log a message as an error } } 

This requires you to only pass instances that match the logic you want to implement for each of the three lines.

0
source

Source: https://habr.com/ru/post/1393966/


All Articles