1. Creating an Object
Here we are, finally talking about creating objects. You've already seen this before, but now we'll dig a bit deeper. Honestly, creating objects is super simple.
To create an object, you use the new operator. Usually, you create a new instance (object) of a class and immediately store it in a variable of the same type.
Class name = new Class(parameters);
Where Class is the object type, name is the variable name (often lowercase, like cat), and to the right of = is the creation of a new object of that class.
Examples:
| Code | Note |
|---|---|
|
Creating an object of type object |
|
Creating an object of type Cat |
|
Creating a StreamReader object with a parameter |
A lot of times, programmers name variables the same as the class, just with a lowercase letter. For a newbie, this code might look confusing:
| Code |
|---|
|
|
|
But actually, there's nothing scary about this code — it's just regular code where you create a variable and immediately initialize it with an object of the same type.
On the left — variable declaration, on the right — creating a new object in memory using new. That's it!
2. Constructor
You've probably seen that when creating an object, sometimes you pass in some parameters. And sometimes you do, sometimes you don't. So how does this whole parameter thing work?
It's simple: every class has a special method (or methods) that handle parameters when creating an object. These methods are called constructors. And a single one is a constructor.
It's easy to spot a constructor method in code. It has two features:
- The constructor's name matches the class name (and starts with a capital letter)
- The constructor doesn't have a return type (not even void is written).
It usually looks like this:
modifiers Class(parameters)
{
constructor code
}
Example of declaring a constructor:
public class Point
{
public int X;
public int Y;
public Point(int x, int y) // Constructor
{
X = x;
Y = y;
}
}
Usage:
Point p = new Point(5, 10); // Calling the constructor
When you create an object with new Point(5, 10), the constructor with two parameters is called, which initializes the X and Y fields.
Sometimes constructor parameters have the same names as the fields — for convenience. This name conflict is solved with the keyword this:
public Point(int x, int y)
{
this.x = x; // this.x — object field, x — constructor parameter
this.y = y;
}
3. Calling the Constructor
When you write new Class(parameters), C#:
- creates a new object in memory,
- calls the appropriate constructor, passing your parameters.
Example with a cat class:
public class Cat
{
public string Name;
public int Age;
public Cat(string name, int age)
{
Name = name;
Age = age;
}
}
Usage:
Cat cat = new Cat("Vaska", 2); // Allowed: calls the constructor with two parameters
Cat cat2 = new Cat("Vaska"); // Not allowed: no such constructor — compile error
Cat cat3 = new Cat(); // Not allowed: no parameterless constructor — compile error
If your class only has a constructor with parameters, you have to provide values for them when creating an object.
4. Multiple Constructors
But if you want, you can add multiple constructors to a class. There's no limit to how many constructors or parameters you can have. When you create an object, the compiler will pick the constructor that matches your parameters.
Example:
public class Cat
{
public const int UNKNOWN = -1;
public string Name;
public int Age;
public Cat(string name, int age)
{
Name = name;
Age = age;
}
public Cat(string name)
{
Name = name;
Age = UNKNOWN; // "Default" value for unknown age
}
}
Usage:
Cat cat1 = new Cat("Vaska", 2); // Uses the first constructor
Cat cat2 = new Cat("Murka"); // Uses the second constructor
Cat cat3 = new Cat(); // Error! No parameterless constructor
We decided to handle the case where the cat's age might be unknown. For that, we added a special constant — UNKNOWN and a constructor that only takes the cat's name.
Notice that we still initialize both class variables inside both constructors. For unknown/missing parameters, we use the UNKNOWN constant.
5. Default Constructor
If your class doesn't have any constructors, the compiler will automatically add an empty parameterless constructor:
public ClassName()
{
}
But if you declare at least one constructor in your class — the empty constructor won't be added automatically.
Example 1:
public class Cat
{
public string Name;
public int Age;
}
// Allowed:
Cat cat = new Cat(); // The default (parameterless) constructor will be called
Example 2:
public class Cat
{
public string Name;
public int Age;
public Cat(string name) { Name = name; }
}
// Not allowed:
Cat cat = new Cat(); // Error: no more parameterless constructor!
6. Variable Initialization
In C#, class variables can be initialized either right when you declare them, or inside the constructor.
Example:
public class Cat
{
public string Name;
public int Age = -1; // Initial value
public Cat(string name, int age)
{
Name = name;
Age = age; // Overwrites the initial value
}
public Cat()
{
Name = "Nameless";
// Age stays -1 (the initial value)
}
}
Explanation:
- When you create with new Cat("Vaska", 2) the Age variable will first be -1, but then the constructor will set it to 2.
- When you create with new Cat() — Age will stay -1.
7. Variable Initialization Order
The data of a new object is initialized in this order:
- Class fields first get default values (0 for int, null for reference types, etc.).
- Then, any initializers you wrote at the field declaration are executed, in the order they appear in the code.
- And only after that, the constructor code runs.
Variables are initialized before the constructor and in the order they're declared. So be careful with dependencies between fields.
Incorrect Example
Non-static fields can't be initialized using other non-static variables:
public class Solution
{
public int a = 1;
public int b = a; // can't use a
public int c = a + b; // can't use a and b
}
// This code will cause a compile error!
Correct Example
For static variables everything works fine:
public class Solution
{
public static int a = 1; // Explicitly set a = 1
public static int b = a + 2; // b = 1 + 2 ⇒ 3
public static int c = a + b + 3; // c = 1 + 3 + 3 ⇒ 7
public Solution()
{
Console.WriteLine($"a = {a}, b = {b}, c = {c}");
// Will print: a = 1, b = 3, c = 7 — exactly as expected
}
}
Correct Example 2
For static fields, you can even write this:
public class Solution
{
public static int a = b + c + 1; // b and c are still 0
public static int b = a + c + 2; // a == 1, c is still 0
public static int c = a + b + 3; // a == 1, b == 3
}
GO TO FULL VERSION