The new constructor should take its own data type as a parameter then call the instance constructor.
Example written below, there is a class called Product which contains two overload constructors. One takes two parameters which are Id and Name, another takes Product data type and pass the properties of Product to another constructor.
public class Product { private int Id; private string Name; public Product(int id, string name) { this.Id = id; this.Name = name; } public Product(Product product) : this (product.Id, product.Name) { } public override string ToString() { return string.Format("Id of {0} is {1}", this.Name, this.Id); } } class Program { static void Main(string[] args) { Product productA = new Product(1, "Fridge"); Product productB = new Product(productA); Console.WriteLine(productB.ToString()); // output : "Id of Fridge is 1" Console.Read(); } }




0 comments:
Post a Comment