Related Articles

Back to Latest Articles

C# Basics – Constructors – Part 12

We explore how constructors work and for what we might need to use them.

Andraz Krzisnik
C# Basics – Constructors – Part...


Sometimes we want to create an object and set some predetermined state to it. Basically, you would pass the properties’ values as an argument to an object when you are creating it. Whenever we are creating a constructor, there is something important to keep in mind, we need to set it’s name exactly the same as the name of the class it’s in.

We also can’t call it just anywhere like functions. We can only call a constructor with a new keyword in the beginning.

class RealEstate
    public string street;
    public int number;
    public string type;

    public RealEstate(string s, int n, string t)
        this.street = s;
        this.number = n;
        this.type = t;

And when we would use it, we’d write:

RealEstate rl = new RealEstate("Some street", 7, "House");
MessageBox.Show("Address: " + rl.street + ", real estate type: " + rl.type);
Download Examples Next Chapter
Show Comments (0)


Related Articles

C# Basics

C# Basics – Random Numbers, Chars and Strings – Part 7

Random Numbers To generate a random number, we will use a constructor called Random. Then to generate a random number we will use either .Next() or .NextDouble() function. Random...

Posted on by Andraz Krzisnik
C# Basics

C# Basics – Functions – Part 10

Functions We’ve been writing simple programs so far. But when things get more complicated, writing it all into one block of code could become hard to read. We can use functions...

Posted on by Andraz Krzisnik