I usually check constructor arguments for null values in the following manner:
public class SomeClass(SomeArgument someArgument) { if(someArgument == null) throw new ArgumentNullException("someArgument"); }
But say I have a class that inherits from another class:
public abstract class TheBase { public TheBase(int id) { } } public class TheArgument { public int TheId { get; set; } } public class TheInheritor : TheBase { public TheInheritor(TheArgument theArgument) : base(theArgument.TheId) { } }
And someone now constructs an instance of TheInheritor
like this:
var theVar = new TheInheritor(null);
I can't think of a way that to check for null
before base
is being called (and throwing a NullReferenceException
). Short of letting TheBase
's constructor accept an instance of TheArgument
I can't see how I could have this sanity-check. But what if TheArgument
is related only to TheInheritor
and there are a lot of other classes inheriting from TheBase
?
Any recommendations on how to solve this?
Order of constructor call for Multiple Inheritance For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new .
The constructor is used when an object is constructed. Most of the work in constructing an object is automatically done by the Java system. Usually you need to write only a few statements that initialize a instance variables.
A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration.
You can do it with something like this:
public TheInheritor(TheArgument theArgument) : base(ConvertToId(theArgument)) { } private static int ConvertToId(TheArgument theArgument) { if (theArgument == null) { throw new ArgumentNullException("theArgument"); } return theArgument.Id; }
Or more generally, something like this:
public TheInheritor(TheArgument theArgument) : base(Preconditions.CheckNotNull(theArgument).Id) { }
where Preconditions
is a utility class elsewhere, like this:
public static class Preconditions { public static T CheckNotNull<T>(T value) where T : class { if (value == null) { throw new ArgumentNullException(); } return value; } }
(This loses the argument name, of course, but you could pass that in as well if necessary.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With