Access Modifiers and Methods - C# Programming for Beginners (2015)

C# Programming for Beginners (2015)

Chapter 7: Access Modifiers and Methods

In the last chapter, we studied what objects and classes are and how the member variables of a class can be initialized via constructor. We also studied different types of constructors. In this chapter, we are going to study how objects act to perform certain functionalities. In object oriented programming (OOP), this is achieved via methods. However, before diving into the details of methods, we shall study another important concept: access modifiers in C#.

Contents

· Access Modifiers

· Methods in C#

1- Access Modifiers

From the beginning of this book, we have been using the keyword “public” with variables. This is one of the five access modifiers available in C#. Access modifiers control access to a particular variable. For instance, a member variable marked “public” can be accessed anywhere. However, a variable marked “private” is accessible only within the class in which it exists. Table 1.0 contains C#’s five access modifiers along with their functionalities.

Access Modifier

Functionality

public

Accessible everywhere

internal

Accessible only to the classes within the assembly and friend assemblies

protected

Accessible only within the class and its derived classes

private

Accessible only within the class

Protected-internal

Accessible where protected or internal are accessible

2- Methods

As aforementioned, C# classes and objects act via methods. To understand the concept of methods in C#, let’s jump straight to the first example of this chapter.

Example1:

Add a new class named “Product” to the existing project. The contents of the “Product” class should be similar to the following code snippet.

Product.cs

using System;

namespaceMyCSharpApplication

{

class Product

{

public string name;

public int price;

public string category;

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

{

this.name = name;

this.price = price;

this.category = category;

}

public void IncreasePrice()

{

price += 10;

}

}

}

The produce class contains three member variables: name, price, and category. The class contains a constructor which initializes these three variables. After the constructor, we have added a method named “IncreasePrice”. The syntax of a method is simple; it starts with an access modifier, which is public in this case. After that, the return type of the method is mentioned. A return type is the type of the value returned by the method. Since our “IncreasePrice” method doesn’t return any value, we specified its return type as void. After the return type, the name of the method is written (in our case, this is “IncreasePrice”). The opening and closing round brackets contain parameters. Since we don’t want our “IncreasePrice” method to accept any parameter, we left the brackets empty. Notice that the method declaration is quite similar to the constructor declaration. A constructor is, in fact, a method with no return type. A method is called using the object of the class by the appending dot operator followed by the method name after the object of the class. Modify the “Program” class so that it looks like the one in following code snippet.

Program.cs

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Product p = new Product("Grapes", 40, "Food");

Console.WriteLine("The price of product "+p.name+ " is: "+p.price);

p.IncreasePrice();

Console.WriteLine("The new price of product " + p.name + " is: " + p.price);

Console.Read();

}

}

}

In the “Program”, we created the object of “Product” class using a parameterized constructor. The initial value of the variable “price” is set to 40. We displayed this price on the console. Then we called the “IncreasePrice” method on the object “p” of the “Product” class. The value of the “price” variable is incremented by 10 every time the “IncreasePrice” method is called. Since we called this method only once, the price is incremented by 10 only once; the new price would be 40+10 = 50. We then printed this new price on the console just to make sure the price was incremented. The output of the code in Example1 is as follows:

Output1:

The price of product Grapes is: 40

The new price of product Grapes is: 50

· Passing Parameters to a Method

Just like we have parameterized constructors, we also have parameterized methods. For instance, instead of increasing the price of the price variable by 10 every time, we can also pass a value of our choice. Types of parameters which a method can accept are mentioned in the round brackets that follow the method name. In the second example, we will see how we can increase the price by the value of our choice by passing the value as a parameter to the “IncreasePrice” method.

Example2:

Change the code in the “Product” and “Program” classes as follows:

Product.cs

using System;

namespaceMyCSharpApplication

{

class Product

{

public string name;

public int price;

public string category;

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

{

this.name = name;

this.price = price;

this.category = category;

}

public void IncreasePrice(int price)

{

this.price += price;

}

}

}

Program.cs

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Product p = new Product("Grapes", 40, "Food");

Console.WriteLine("The price of product "+p.name+ " is: "+p.price);

p.IncreasePrice(25);

Console.WriteLine("The new price of product " + p.name + " is: " + p.price);

Console.Read();

}

}

}

Output2:

The price of product Grapes is: 40

The new price of product Grapes is: 65

· Returning Values From Method

In both of our first two examples, the method “IncreasePrice” did not return any value. The return type of the method was void. However, we can also force a method to return a value by changing its return type. For instance, we can retrieve the increased price from the “IncreasePrice” method by changing its return type to “int” and then using “return” at the end of the method, followed by the value to be returned. This is explained in the following example.

Example3:

Change the code in the “Product” and “Program” classes as follows:

Product.cs

using System;

namespaceMyCSharpApplication

{

class Product

{

public string name;

public int price;

public string category;

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

{

this.name = name;

this.price = price;

this.category = category;

}

publicintIncreasePrice(int price)

{

this.price += price;

returnthis.price;

}

}

}

Program.cs

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Product p = new Product("Grapes", 40, "Food");

Console.WriteLine("The price of product "+p.name+ "is: "+p.price);

Console.WriteLine("The new price of product " + p.name + "is: " + p.IncreasePrice(20));

Console.Read();

}

}

}

Output3:

The price of product Grapesis: 40

The new price of product Grapesis: 60

Exercise 7

Task:

Create a class named “Car”. Create two variables named “name” and “speed” inside the class. Initialize these variables using a parameterized constructor. Create a method inside the “Car” class. This method should accept an integer value and decrease the speed of the car by that value. The method should return the decreased speed to the calling function. In the “Program” class, display the decreased speed on console.

Solution:

Car Class:

using System;

usingSystem.Collections.Generic;

namespaceMyCSharpApplication

{

class Car

{

public string name;

publicint speed;

public Car(string name, int speed)

{

this.name = name;

this.speed = speed;

}

publicintDecreaseSpeed(int speed)

{

this.speed -= speed;

returnthis.speed;

}

}

}

Program Class:

using System;

usingSystem.Diagnostics;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

Car c = new Car("Ford", 105);

Console.WriteLine("Initial Speed of car is "+c.speed);

Console.WriteLine("Decreased Speed of car is " + c.DecreaseSpeed(15));

Console.Read();

}

}

}