O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Instance Constructors

During the creation of a new instance of a class, one often wants to run some code to initialize the state associated with the instance being created. Examples include setting fields or running other initialization tasks.

As such, constructors are special kinds of methods that cannot be called directly but are invoked through the use of the new operator. Parameters can be used on a constructor definition to pass data to the newly created object. To declare such an instance constructor, you define what looks like a method but has the name of the class and omits a return type:

class Person{    private readonly string _name;    private readonly int _age;    public Person(string name, int age)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required