Say I have something like this:
public class BaseClass
{
public BaseClass(string someString)
{
if(someString == null)
throw new ArgumentException();
}
}
public class ChildClass : BaseClass
{
public ChildClass(string someString)
: base(someString)
{
// Should I do this??
if(someString == null)
throw new ArgumentException();
}
}
Also, what if I’m inheriting a class that I do not have the source for. Should I recheck constructor arguments?
4
No. If your base class validates something you don’t have to. As for your second question: Yes and No. Yes if you’re going to use the argument, no if only the base class uses the argument.
It’s the base classes job to be sure that value is good enough for its purpose, you can’t however expect the base class to ensure the value is good enough for your purpose. For all you know the base class is completely happy with a null value and can function fine in that scenario when you can’t.
Also when null checking your strings, you usually want string.IsNullOrWhitespace(someString)
or string.IsNullOrEmpty(someString)
depending on whether or not ” ” is valid, or “” is valid, or neither.
2