5

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.

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88

2 Answers2

7
public CustomException(string customField) : this(customField,"")
{
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 2
    Thanks, but this is assuming that the base class uses the empty string as a default. This may be close enough for the Exception class, but is not guaranteed to be true in general. For the public CustomException(string customField) constructor, no call should ideally be made to the base constructor at all. – Zaid Masud Aug 22 '12 at 11:43
3

Factor it out into a separate method, and call that method from both constructors.

public class CustomException : Exception
{
    private readonly string _customField;

    public CustomException(string customField, string message)
        : base(message)
    {
        Init(out _customField, customField);
    }

    public CustomException(string customField)
        : base()
    {
        Init(out _customField, customField);
    }

    private Init(out string _customField, string customField)
    {
        _customField = customField;
    }
}
  • Compile error: A readonly field cannot be assigned to (except in a constructor or a variable initializer). As mentioned in my question, I'd like to keep the field readonly. – Zaid Masud Aug 22 '12 at 11:49
  • @ZaidMasud No, no compile error. In `Init`, `_customField` is an `out` parameter which refers to the field, but not the field itself. –  Aug 22 '12 at 11:50
  • Ahh... see the edit now. Interesting syntax to see the parameter as both an out and not an out as well. Need to test this out. – Zaid Masud Aug 22 '12 at 11:52
  • In my earlier version, I had `ref`, which would work just as well, but `out` is nicer. –  Aug 22 '12 at 11:53
  • +1 for interesting syntax that I haven't seen before and that accomplishes the task. Still an unusual approach, and the Init method signatures starts to grow faster than you'd like if you have more parameters (x2). – Zaid Masud Aug 22 '12 at 12:52
  • True, passing each readonly field that needs setting can lead to a long argument list. –  Aug 22 '12 at 12:54