Home > Software design >  Chaining overloaded constructors in C#
Chaining overloaded constructors in C#

Time:02-17

I'm quite new in C# and I'm not sure if I can refactor this class to make these constructors chaining.

I've tried from examples on The Internet, but all of them explain how to chain constructors with a number of parameters in ascending order. I've got constructors here that got two parameters each because the constructor is overloaded. Hope my explanation makes sense.

I'm really struggling with this and any help will be really appreciated.

public class MyException: TheException
    {
        public MyException()
        : base()
        {
        }

        public MyException(string message)
        : base(message)
        {           
        }

        public MyException(string message, Exception inner)
        : base(message, inner)
        {
        }

        public MyException(string message, string outcome, Exception inner)
            : base(message, outcome, inner)
        { 
        }

        public MyException(string message, string outcome)
            : base(message, outcome)
        {
        }
}

CodePudding user response:

You can use this instead of base to chain your constructors. You need to provide your default values. Here's an example.

public class MyException: TheException
{
    public MyException()
    : this("default message")
    {
    }
    
    // assuming here you want to call other overload with Exception, not with outcome
    public MyException(string message)
    : this(message, (Exception)null)
    {           
    }

    public MyException(string message, Exception inner)
    : this(message, null, inner)
    {
    }

    public MyException(string message, string outcome)
        : this(message, outcome, null)
    {
    }

    public MyException(string message, string outcome, Exception inner)
        : base(message, outcome, inner)
    { 
    }
}
  •  Tags:  
  • c#
  • Related