What a class is
C# is an object-oriented language, and a class is the way you define your own type. It is a blueprint: it lists the data an object holds, called fields, and the actions an object can perform, called methods. An object (also called an instance) is one concrete thing built from that blueprint, with its own values. A class Employee describes what every employee has; one object is the employee named Andrew who is 30.
The smallest class is an empty one:
class Employee {
}
Creating objects
The new keyword creates an object of a class and returns a reference to it:
Employee employee = new Employee();
You can create as many objects from one class as you like. Each one is independent.
Fields
A field is a variable declared inside a class. Every object gets its own copy, so changing a field on one object doesn't affect the others. Strings in C# use double quotes, and the dot operator reads or writes a field:
class Employee {
public string name;
public int age;
}
Employee emp1 = new Employee();
emp1.name = "Andrew";
Console.WriteLine(emp1.name); // Andrew
Employee emp2 = new Employee();
emp2.age = 40;
Console.WriteLine(emp2.age); // 40
Console.WriteLine(emp1.age); // 0
A field that you never assign still has a value: 0 for numbers, false for bool and null for a string or any other class type. That's why emp1.age prints 0.
The word public is an access modifier. A public member can be used from any other class. Without a modifier, a class member is private, which means only code inside the class can see it.
Constructors
Setting fields one by one after new is clumsy, and it is easy to forget one. A constructor is a special method that runs when the object is created, so it can set the starting values. It has the same name as the class and no return type, not even void:
class Employee {
public string name;
public int age;
public Employee(string name, int age) {
this.name = name;
this.age = age;
}
}
Employee emp1 = new Employee("Andrew", 30);
Employee emp2 = new Employee("Mary", 25);
Notice the parameter names are the same as the field names. Inside the constructor, the parameter hides the field. this is a reference to the object being built, so this.name means the field and plain name means the parameter. The line this.name = name; copies the argument into the field. Outside of cases like this one, this is optional.
Methods
Methods are functions that belong to a class, and they work on the data of the object they are called on. By convention, C# method names use PascalCase, so PrintName rather than printName:
class Employee {
public string name;
public int age;
public Employee(string name, int age) {
this.name = name;
this.age = age;
}
public void PrintName() {
Console.WriteLine(name);
}
public void PrintEmployee() {
PrintName();
Console.WriteLine(age);
}
}
Employee emp1 = new Employee("Andrew", 30);
emp1.PrintEmployee(); // Andrew, then 30
Employee emp2 = new Employee("Mary", 25);
emp2.PrintEmployee(); // Mary, then 25
A method calls another method of the same class by its plain name, and it reads its fields the same way. Which object's fields it sees depends on the object you called it on: emp1.PrintEmployee() uses Andrew's data and emp2.PrintEmployee() uses Mary's. Each of those calls prints the name and then the age on separate lines.
Classes are reference types
A variable of a class type holds a reference to an object, not the object itself. Copying the variable copies the reference, so both variables refer to the same object:
Employee a = new Employee("A", 1);
Employee b = a;
b.age = 99;
Console.WriteLine(a.age); // 99
Common mistakes
- Single quotes for text.
'Andrew'is not a string. Acharholds one character, so use"Andrew". - Lowercase type names. The type is
string(orString), and class names such asJobare conventionally capitalised. C# is case-sensitive, sohireMe()doesn't match a method calledHireMe. - A return type on a constructor.
public void Job(string title)declares an ordinary method namedJob, not a constructor. - Forgetting
this.when names clash. Writingtitle = title;inside the constructor assigns the parameter to itself and leaves the field unchanged. The compiler warns about it. - Forgetting
public. A private method can't be called from another class, such asSolution.
The exercise, step by step
The exercise asks for a Job class and then uses it inside MainFunction.
- Declare the class. Write
class JobaboveSolution; it is the blueprint. - Add the field.
public string title;stores each job's title. - Add the constructor.
public Job(string title)has the class name and no return type, and takes the title when the object is created. - Store the title.
this.title = title;copies the parameter into the field. - Add
HireMe. Declare itpublic void, with PascalCase. - Print the message. Inside it,
Console.WriteLine("You're hired as a " + title);joins the text and the field. Here no parameter hides the field, so the plain name works. - Create the object. In
MainFunction,Job job = new Job("Software Engineer");. - Call the method.
job.HireMe();printsYou're hired as a Software Engineer.
class Job {
public string title;
public Job(string title) {
this.title = title;
}
public void HireMe() {
Console.WriteLine("You're hired as a " + title);
}
};
class Solution {
public void MainFunction() {
Job job = new Job("Software Engineer");
job.HireMe();
}
}
The semicolon after the closing brace of Job is allowed in C# but not needed.
Key takeaways
- A class is a blueprint;
newbuilds an object from it. - Each object has its own copy of the fields.
- A constructor shares the class's name, has no return type, and sets up the object.
thisrefers to the current object and resolves name clashes with parameters.- Variables of a class type hold references, so assigning one to another shares the object.