In C# if one wishes to use C# constructor overloading they can use the “this” keyword right after to initialize the object, the only thing to note is one will not be able to do any validation of the data using this method.
Below I have listed 3 ways that one can initialize constructor overload in C#. There is also a base keyword that one can use to call the base class in their constructor initialization code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//initialize without checking, use the this keyword public Person(Person p) : this(p.Name, p.Age) { } //provide a method to initialize public Person(string name, int age) { Initialize(name, age); } //validate the input public Person(Person p) { if (p == null) throw new ArgumentNullException("p"); Initialize(p.Name, p.Age); } private void Initialize(string name, int age) { Name = name; Age = age; } //initialize the base class public Person(string name, int age): base(name, age) { } |
Leave A Comment