i want to understand how c# class with 3 constructers with mismatching base parameters work

Hi,

In one of the projects that i work  at i have come accross a class like below,

could yo help me how it works ? because i did not fully got how base can have 2 parameters but the constructer takes 3 and i did not fully understand the first 3 constructers using this how it works?


public class CustomHttpException : Exception
    {
        public CustomHttpException(string message) : this(message, HttpStatusCode.InternalServerError, null) { }
        public CustomHttpException(string message, Exception innerException) : this(message, HttpStatusCode.InternalServerError, innerException) { }
        public CustomHttpException(string message, HttpStatusCode statusCode) : this(message, statusCode, null) { }
        
        public CustomHttpException(string message, HttpStatusCode statusCode, Exception innerException)
            : base(message, innerException)
        {
            StatusCode = statusCode;
        }

        public HttpStatusCode StatusCode { get; set; }
    }

Open in new window

nicedoneAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Constructor overloads work the same as method overloads, because constructors are methods themselves--just special methods. When you overload a method, there's nothing specified in the language that states you must call the other methods. We overload methods so that we can provide default values for some or all of the method's parameters. The same thing is happening in your code above. Yes, you have a constructor that takes in 3 parameters. Calling the base constructor with only 2 of those parameters tells me that the third parameter is getting some kind of default value (as specified by the base constructor itself, internally). This is completely fine, and normal.
Guy Hengel [angelIII / a3]Billing EngineerCommented:
this is for compilation of the code that is calling the constructor.

for this line:
CustomHttpException x = new CustomHttpException ("some string");

only the first constructor can be taken, and it matches with the data types.

with this line of code, the compiler will check what type of object "some_exception" is:
CustomHttpException x = new CustomHttpException ("some string", some_exception);

if it is of type Exception, then the 2nd constructor is used
if it is of type HttpStatusCode , then the 3rd constructor is used
if its neither of the 2 types, a compile error will be returned

the last contructor is bascially just having 1 more argument, and using one of the of the other constructors + some function code to do the rest (what the other constructor is not doing)
louisfrCommented:
The 'this' keyword means: first, call another constructor of this class with the provided arguments, then run the body of this constructor.
The 'base' keyword means: first call a constructor of the base class with the provided arguments, then run the body of this constructor.
Every constructor without a 'this' keyword has a 'base' call. If not explicitly written, it's base(), a call to a parameterless constructor of the base class.

As an example:
new CustomHttpException("some message")

Open in new window


There is only one argument, the first constructor of CustomHttpException is called.
The 'this' keyword tells us to call a constructor of CustomHttpException with 3 arguments: message, HttpStatusCode.InternalServerError, null.
The third constructor is the only one with three parameters.
The 'base' keyword tells us to call a constructor of the base class Exception with 2 arguments: message, innerException.
it_saigeDeveloperCommented:
And to put a face on what was explained here.  Consider the following -
using System;

namespace EE_Q28688296
{
	class Program
	{
		static void Main(string[] args)
		{
			Derived derived = new Derived(1);
			Console.WriteLine(derived);
			Console.WriteLine();

			derived = new Derived(1, Gender.Undeclared);
			Console.WriteLine(derived);
			Console.WriteLine();

			derived = new Derived(1, "Terri");
			Console.WriteLine(derived);
			Console.WriteLine();

			derived = new Derived(1, Gender.Male, "Terri");
			Console.WriteLine(derived);
			Console.WriteLine();
			Console.ReadLine();
		}
	}

	class Base
	{
		private int fID;
		private string fName;

		private Base() { ;}

		public Base(int ID, string Name)
		{
			Console.WriteLine("In the base constructor");
			this.ID = ID;
			this.Name = Name;
		}

		public int ID
		{
			get { return fID; }
			set 
			{
				Console.WriteLine("Setting the ID field to - {0}", value);
				fID = value; 
			}
		}
		public string Name
		{
			get { return fName; }
			set 
			{
				Console.WriteLine("Setting the Name field to - {0}", !string.IsNullOrEmpty(value) ? value : "Unnamed");
				fName = !string.IsNullOrEmpty(value) ? value : "Unnamed";
			}
		}

		public override string ToString()
		{
			return string.Format("[{0}] {1}", ID, !string.IsNullOrEmpty(Name) ? Name : "Unnamed");
		}
	}

	class Derived : Base
	{
		private Gender fGender;

		public Derived(int ID)
			: this(ID, Gender.Unknown, string.Empty) 
		{
			Console.WriteLine("In the derived constructor with one parameter - ID");
		}

		public Derived(int ID, string Name) : this(ID, Gender.Unknown, Name) 
		{
			Console.WriteLine("In the derived constructor with two parameters - ID and Name");
		}

		public Derived(int ID, Gender Gender) : this(ID, Gender, string.Empty) 
		{
			Console.WriteLine("In the derived constructor with two parameters - ID and Gender");
		}

		public Derived(int ID, Gender Gender, string Name) : base(ID, Name)
		{
			Console.WriteLine("In the derived constructor with three parameters - ID, Gender and Name");
			this.Gender = Gender;
		}

		public Gender Gender
		{
			get { return fGender; }
			set 
			{
				Console.WriteLine("Setting the Gender field to - {0}", value);
				fGender = value; 
			}
		}

		public override string ToString()
		{
			switch (Gender)
			{
				case Gender.Male:
				case Gender.Female:
					return string.Format("{0} is a {1}", base.ToString(), Gender);
				case Gender.Undeclared:
					return string.Format("{0} did not declare their gender.", base.ToString());
				case Gender.Unknown:
				default:
					return string.Format("{0} does not have a gender defined", base.ToString());
			}
		}
	}

	enum Gender : int
	{
		Unknown = 0,
		Male = 1,
		Female = 2,
		Undeclared = 3
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.