Start learning free

LESSON 175 OF 347 · FUNCTIONS & CLASSES

Classes in C#: Fields, Constructors and Methods

Lesson Read the full explanation

Java is an object oriented programming language. Almost everything in Java is an object, with its attributes and methods.

Class creates a user-defined data structure, which holds its own data members (attributes) and member functions (methods), which can be accessed and used by creating an instance of that class.

Classes are like a blueprint for objects outlining possible behaviors and states that every object of a certain type could have.

Classes are defined via the keyword class, like this:

// Define an empty class Employee
class Employee {

};

Objects/Instances

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual employee, like a person named "Andrew" who is 30 years old.

You can have many employees to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.

After a class is defined, we can create objects of the class using the new keyword like this:

// Define an empty class Employee
class Employee {

};

// inside main function:
Employee employee = new Employee();

Attributes/Properties

A class attribute is a Java variable that belongs to a class and is shared between all the objects of this class. Let's add some attributes to our Employee class:

class Employee {
	public string name;
	public int age;
};

// inside main function:
Employee emp1 = new Employee();
	
emp1.name = 'Andrew';
Console.WriteLine(emp1.name); // prints 'Andrew'
	
Employee emp2 = new Employee();
	
emp2.age = 40;
Console.WriteLine(emp2.age); // prints 40

We added two properties: the String name and the int age. Then, we created two different Employee objects emp1 and emp2.

The attributes of objects can be accessed and modified using the dot operator (.), like we did above with emp1.name and emp2.age.

The keyword public used inside the class is called an access specifier. name and age are public attributes, whch means they can be accessed from anywhere in the code, not just inside the class code.

Constructors

In real life, we want to set the attributes specific to each object when creating it. For example, an employee named Andrew of 30 years old and another one named Mary of 25 years old. Here the constructor comes to rescue.

A constructor is a special type of method (function) which is used to initialize the instance members of the class.

In Java the constructor method has the same name as that of its class and is always called when an object is created.

Let's add a constructor to our Employee class:

class Employee {
	public string name;
	public int age;
	
	// constructor:
	public Employee(string name, int age) {
		this.name = name;
		this.age = age;
	}
};

// inside main function:
Employee emp1 = new Employee('Andrew', 30);
	
Console.WriteLine(emp1.name);
	
Employee emp2 = new Employee('Mary', 25);

Console.WriteLine(emp2.age);

// prints 'Andrew' and 25 on different lines

The "this"

Every object in Java has access to its own address through an important refference called this.

The this refference is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to access and manipulate the attributes of that object, like we did above with this.name = name.

Member functions

Member functions are functions that belong to the class:

class Employee {
	public string name;
	public int age;
	
	// constructor:
	public Employee(string name, int age) {
		this.name = name;
		this.age = age;
	}
	
	//member functions:
	public void printName() {
		Console.WriteLine(name); // it is not mandatory to use "this" to access an attribute
	}
		
	public void printEmployee() {
		printName();
		Console.WriteLine(age);
	}
};

// inside main function:
Employee emp1 = new Employee('Andrew', 30);

emp1.printEmployee(); // prints "Andrew", 30
	
Employee emp2 = new Employee('Mary', 25);

emp2.printEmployee(); // prints "Mary", 25

As you can see, we access functions just like we access attributes: using the dot syntax (.).

The function call uses the attributes of the object it was called on. That's why the first printEmployee() prints 'Andrew' and 30 and the second prints 'Mary' and 25.


Assignment
Follow the Coding Tutorial and let's write some classes.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 8
    Ctrl + Enter to check

    C# · FUNCTIONS & CLASSES

    Classes in C#, explained

    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. A char holds one character, so use "Andrew".
    • Lowercase type names. The type is string (or String), and class names such as Job are conventionally capitalised. C# is case-sensitive, so hireMe() doesn't match a method called HireMe.
    • A return type on a constructor. public void Job(string title) declares an ordinary method named Job, not a constructor.
    • Forgetting this. when names clash. Writing title = 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 as Solution.

    The exercise, step by step

    The exercise asks for a Job class and then uses it inside MainFunction.

    1. Declare the class. Write class Job above Solution; it is the blueprint.
    2. Add the field. public string title; stores each job's title.
    3. Add the constructor. public Job(string title) has the class name and no return type, and takes the title when the object is created.
    4. Store the title. this.title = title; copies the parameter into the field.
    5. Add HireMe. Declare it public void, with PascalCase.
    6. 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.
    7. Create the object. In MainFunction, Job job = new Job("Software Engineer");.
    8. Call the method. job.HireMe(); prints You'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; new builds 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.
    • this refers 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.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free