Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When chaining a base constructor, how can I reuse initialization code in an overload

Tags:

c#

.net

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.

like image 998
Zaid Masud Avatar asked Aug 22 '12 11:08

Zaid Masud


People also ask

Can constructor call another overloaded constructor?

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.

Can we overload private constructor C#?

We can overload the constructor if the number of parameters in a constructor are different.

What is the use of constructor chaining in C#?

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.


1 Answers

public CustomException(string customField) : this(customField,"")
{
}
like image 191
L.B Avatar answered Sep 19 '22 16:09

L.B