Best way to guard against bad constructor arguments?

Let's say I have a class called MyClass. MyClass has a private variable foo of type string. MyClass also has a private variable bar of type List<string>. MyClass also has a constructor. This constructor takes one argument of type string. I only want this constructor to create a MyClass object if the argument passed to the constructor contains a value in the private List bar. How do I prevent object construction if a bad value is given? Below is my example code:

class MyClass { private string foo; private List<string> bar = new List<string> { "ab", "cd", "ef" }; public MyClass(string arg) { if(bar.contains(arg) == true) { = arg; } else { ??? } } } 

by Xarcies via /r/csharp

Leave a Reply