CSharp examples for Custom Type:Constructor
A class or struct may overload constructors.
To avoid code duplication, one constructor may call another, using the this keyword:
using System; public class Product { public decimal Price; public int Year; public Product (decimal price) { Price = price; } public Product (decimal price, int year) : this (price) { Year = year; } }
When one constructor calls another, the called constructor executes first.
You can pass an expression into another constructor as follows:
public Product (decimal price, DateTime year) : this (price, year.Year) { }
For classes, the C# compiler automatically generates a parameterless public constructor if and only if you do not define any constructors.
If you define at least one constructor, the parameterless constructor is no longer automatically generated.