Please see question embedded in comment below.
public class CustomException : Exception
{
private readonly string _customField;
public CustomException(string customField, string message)
: base(message)
{
// What's the best way to reuse the customField initialization code in the
// overloaded constructor? Something like this(customField)
}
public CustomException(string customField)
{
_customField = customField;
}
}
I'm open to considering alternative implementations that reuse the base constructor and minimize initialization code. I'd like to keep the _customField readonly, which is not possible if I extract a separate initialization method.
We can call an overloaded constructor from another constructor using this keyword but the constructor must be belong to the same class, because this keyword is pointing the members of same class in which this is used. This type of calling the overloaded constructor also termed as Constructor Chaining.
We can overload the constructor if the number of parameters in a constructor are different.
Constructor Chaining is an approach where a constructor calls another constructor in the same or base class. Even though the above approach solves our problem, it duplicates code. (We are assigning a value to ' _id ' in all our constructors). This is where constructor chaining is very useful.
public CustomException(string customField) : this(customField,"")
{
}
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