Objects and Classes - C# Programming for Beginners (2015)

C# Programming for Beginners (2015)

Chapter 6: Objects and Classes

In the first five chapters, we covered most of the basic C# programming concepts. From this chapter onwards, we are going to study some of the advanced programming concepts, starting with object oriented programming. In object oriented programming (OOP), all the software components are viewed in the context of real world objects. For instance, you are developing some car racing game; you will identify the objects in the real world car racing. A driver can be an object, a car can be another object, and steering is also an object. When you develop your game you will create these objects in your program. These objects will interact with each other, resulting in fully functional racing car game. This is just a crude example of how modules are developed in OOP programming. OOP offers advantages such as code modularity, usability, and maintainability.

Contents

· Objects and Classes

· Constructor

1- Objects and Classes

Anything which has some properties and can perform some functions is worthy of being implemented as an object in an OOP. As aforementioned, a player in a racing car game can be considered an object since it contains properties like a name, age, country, etc. A player can also perform functions like starting the car, increasing the speed, turning left, turning right, etc. A player is a perfect candidate for being implemented as an object.

Before diving into the code, an important distinction needs to be made here between a class and an object. A class is similar to a blue print. It has no physical existence in the memory. Class depicts how the object looks. Multiple objects can be created from one class. An object, on the other hand, has an actual physical existence in the memory. A class is like a blueprint while an object is the house built according to that blueprint.

To see how objects are created, have a look at the first example of this chapter.

Example1:

Add a new class to your project and name it “Player”. The contents of the player class should be exactly like the following code snippet.

class Player

{

string name;

int age;

string country;

}

This is the structure of the player class. From this structure, it can be assumed that the object of the class will contain three variables: name, age, and country. The memory occupied by the object of the player will be roughly equal to the sum of the memories occupied by the variables name, age, and country. The “Player” class would have been created in the same namespace in which your “Program” class resides.

Open the “Program” class code and make following changes.

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Player p = new Player();

p.name = "Alan";

p.age = 25;

p.country = "USA";

Console.WriteLine(p.name +","+p.age+","+p.country);

Console.Read();

}

}

}


In the Program.cs file above, we created an object “p” in the “Player” class. To create an object of any class, use the “new” keyword followed by the constructor of the class. We will dig deeper into constructors in the next section. For now, assume that “Player()” is the default constructor of the “Player” class. Calling “new” followed by the constructor of any class creates an object of that class in memory and returns its reference. This reference can be stored in the variable of that class. In Example1, we created a variable “p” in class “Player”. This variable “p” stores the reference of the object in the “Player” class. To access the members of an object, use the reference variable then a dot (.) followed by the property that you want to access. For instance, if you want to access the name of the object “p”, you will use p.name. In this way, we stored three random values in name, age, and country. Finally, we print these values on the output console.

Output1:

Alan,25,USA

2- Constructor

A constructor is a function which creates an object of a class and returns its reference to the calling function. The name of the constructor is exactly the same as the name of the class in which it is written. A constructor has no return type, not even void. A constructor can also be used to initialize the member variables of the class when the object is being created. In the second example of this chapter, we will see how a constructor can be used to initialize member variables.

Example2:

Make the following changes in the “Player” class you created in Example1.

using System;

namespaceMyCSharpApplication

{

class Player

{

public string name;

publicint age;

public string country;

public Player()

{

name = "Scott";

age = 30;

country = "UK";

}

}

}

In the above code, we created a constructor which initializes the variables name, age, and country. Name becomes “Scott”, age becomes “30”, and country becomes “UK”. When the object of this class is created calling this constructor, these three variables will automatically be initialized and will be readily available for printing on screen. To see their values on the console, make the following changes in the “Program” class.

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Player p = new Player();

Console.WriteLine(p.name +","+p.age+","+p.country);

Console.Read();

}

}

}

The output of the code in Example2 is as follows:

Output2:

Scott,30,UK

· Parameterized Constructor

You can also initialize the member variables of the class using a constructor by passing arguments to the constructor while creating the object of the class. The constructor, which takes parameter from the calling function, is called a parameterized constructor. Example3 demonstrates usage of the parameterized constructor in C#.

Example3:

Make the following changes in the Player class:

using System;

namespaceMyCSharpApplication

{

class Player

{

public string name;

publicint age;

public string country;

public Player(string name, int age, string country)

{

this.name = name;

this.age = age;

this.country = country;

}

}

}

In the above code snippet, we have entered three variables in the round brackets after the constructor name. These are the parameters, which are separated by commas. To call this constructor, we have to pass three parameters in the call to constructor. These parameters should match the parameter type in the constructor declaration. Also, the order of the passed parameters should match the order of the parameters in the constructor declaration. For instance, in the call to this parameterized constructor, the first parameter should be string, the second should be integer, and the third should be again string. Make the following changes in the “Program” class to see how this works.

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Player p = new Player("Joseph", 35, "Italy");

Console.WriteLine(p.name +","+p.age+","+p.country);

Console.Read();

}

}

}

The output of the code in Example3 is as follows:

Output3:

Joseph,35,Italy

· Overloaded Constructor

You can have two or more parameterized constructors in your class. When the object of the class is created, the constructor whose parameters match with the parameter in the call to the constructor would be called. This concept sounds confusing at first. The fourth example of this chapter demonstrates the concept of an overloaded constructor.

Example4:

Make the following changes in the “Player” class.

Player.cs

using System;

namespaceMyCSharpApplication

{

class Player

{

public string name;

publicint age;

public string country;

public Player(string name, int age, string country)

{

this.name = name;

this.age = age;

this.country = country;

}

public Player(string name)

{

this.name = name;

}

}

}

In the “Player” class, you can see that now there are two parameterized constructors. The first constructor is similar to the one in Example3 and it takes three parameters. The second constructor takes one parameter. The constructor that is called when an object is created depends on the call to the constructor. If the call contains one string type parameter, the second constructor will be called. However, if the call contains three parameters(string, int, string), the first constructor would be called.

Make the following changes in the “Program” class to see difference between the calls to the two constructors in the “Player” class.

Program.cs

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Player p = new Player("Joseph", 35, "Italy");

Player p2 = new Player("Susan");

p2.age = 40;

p2.country = "France";

Console.WriteLine(p.name + "," + p.age + "," + p.country);

Console.WriteLine(p2.name +","+p2.age+","+p2.country);

Console.Read();

}

}

}

The output of the code in Example4 is as follows:

Output4:

Joseph,35,Italy

Susan,40,France

Exercise 6

Task:

Create a class named “Product” with three properties: name, price, and category. Add a parameterized constructor which initializes these three properties. Add another constructor which initializes the first two properties. In the “Program” class, create two objects of “Product” class by calling the two overloaded constructors of the “Player” class. Display the properties of both objects on the console.

Solution:

Product Class:

using System;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceMyCSharpApplication

{

class Product

{

public string name;

publicint price;

public string category;

public Product(string name, int price, string category)

{

this.name = name;

this.price = price;

this.category = category;

}

public Product(string name, int price)

{

this.name = name;

this.price = price;

}

}

}

Program Class

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Product p = new Product("Laptop", 40, "Electronics");

Product p2 = new Product("Apple", 2);

p2.category = "Fruits";

Console.WriteLine(p2.name +","+p2.price+","+p2.category);

Console.WriteLine(p.name + "," + p.price + "," + p.category);

Console.Read();

}

}

}