Constructors in C# are methods invoked during initialization of an object.
They're used to initialize the properties within the object.
using System;
public class Book
{
public string Title { get; set; }
public Book(string title)
{
Title = title;
}
}
Here we have a class Book containing one property called Title.It also contains definition of the constructor initializing the Title property with the value passed as a a parameter.
The name of the constructor is always the same as the name of the class.
public class Program
{
public static void Main()
{
var book = new Book("Harry Potter");
Console.WriteLine(book.Title);
}
}
We can use the Main method to initialize new variable called book with the Book class constructor and display the Title property using Console.WriteLine.Static constructors are a little bit more advanced.
public class Program
{
public static string Material { get; set; }
static Book()
{
Material = "Paper;
}
}
Static constructors are used to initialize static properties.The static properties can be accessed without initialization of the object.
public class Program
{
public static void Main()
{
Console.WriteLine(Book.Material);
}
}