Constructor parameter validation in C# - Best practices
https://softwareengineering.stackexchange.com/questions/51062
-
31-10-2019 - |
Question
What is the best practice for constructor parameter validation?
Suppose a simple bit of C#:
public class MyClass
{
public MyClass(string text)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentException("Text cannot be empty");
// continue with normal construction
}
}
Would it be acceptable to throw an exception?
The alternative I encountered was pre-validation, before instantiating:
public class CallingClass
{
public MyClass MakeMyClass(string text)
{
if (String.IsNullOrEmpty(text))
{
MessageBox.Show("Text cannot be empty");
return null;
}
else
{
return new MyClass(text);
}
}
}
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with softwareengineering.stackexchange