Вы находитесь на странице: 1из 12

Lecture 4

Lecture 4 C# Basic
Introduction to classes and objects in C#
This lecture covers:
 Classes and objects
o Add new class to a Console project and develop it.
o Create and add methods with and without parameters
o Declare and use instances of a class (objects)
o Working with instance varaiables (class level variables)
o Creating and using property blocks, set and get accessors
o Access modifiers public and private
 More about methods
o Static methods
o Passing parameters to methods
 by value
 by reference
 out parameter

It is recommended to read about classes, objects and constructors in the book and/or the
powerPoint slides, before reading this lecture, in order to be familiar with those concepts
before writing code .

1. Create classes
We will declare a class, Account, with a method, and instantiate an object of this class, and
then we will develop an application that tests this class. This test application allows the user to
read his/her account in the bank and to deposit some money to the bank..

Start by crerating a Console application, Classes_Objects and rename the class from Program
to Accounts (Note that the name is plural). In order to rename a class, you can right click on
the class name in solution explorer and choose ‘Rename’. Now add a class, Account to the
project (here the name is singular). In order to do that, right-click the project name, select
Add/ New Items and click Class icon. Change the name from the default Class1.cs to
Account.cs. Add public before the keyword class (for both classes).

In the class Account, write a method ShowMessage that prints a welcome message:
using System;

namespace Classes_Objects
{
public class Account
{ //method ShowMessage
public void ShowMessage()
{
Console.WriteLine("Welcome to the Account Book!");
}
}
}

In application’s Main method, declare an object of the type Account. The syntax is
nazila.hasanzade@hkr.se 1
Last updated 2018 July
Lecture 4

ClassName objectName = new ClassName();

Which will be like that in our example:

Account myAccount = new Account();

The new object now exists but it has no attributes. You can call its method by using dot
operator (.) as:

objectName.methodName();

Which will be like that in our example:


myAccount.ShowMessage();

Analyze the code that instantiates an instance (object) of a class and call its method:

using System;

namespace Classes_Objects
{
public class Accounts
{
//Main method is application's entry point
public static void Main(string[] args)
{
//creat an Account object and assign it to myAccount
Account myAccount = new Account();

//call myAccount's ShowMessage method


myAccount.ShowMessage();
}//end method Main
}//end class Accounts
}//end namespace

Run the application and you see the welcome message.

Remark: You have now created a C# console project, Accounts, and you have added a class,
Account, to the Accounts project. The class diagram of the Account class looks like this:

2. Methods with parameters


Now extend the existing Account class in your application by declaring a method with a
parameter. The new method Deposit has a parameter which represents the deposit amount:
nazila.hasanzade@hkr.se 2
Last updated 2018 July
Lecture 4

public class Account


{
//Add empty constructor
public Account()
{
}// end constructor

//method ShowMessage
public void ShowMessage(string message)
{
Console.WriteLine(message);
}
//method Deposit
public double Deposit(double depositAmount)
{
//you get a 5% bonus
return depositAmount * 1.05;
}// end methos Deposit
}//end of class

Modify the application Accounts to use the new method Deposit:

public static void Main(string[] args)


{
//create an Account object, initialize it and assign it to myAccount
Account myAccount = new Account();

//call myAccount's ShowMessage method with a parameter


myAccount.ShowMessage("Welcome to the Account Book!");

//call myAccount's ShowMessage method with a parameter


myAccount.ShowMessage("Your balance is " + 0);

//prompt the account user to enter the amount


Console.Write("Enter the deposit amount: ");

//call myAccount's Deposit method with the read amount as parameter


//and assign returned value to variable newBalance
double newBalance = myAccount.Deposit(double.Parse(Console.ReadLine()));

//call myAccount's ShowMessage method with another parameter


myAccount.ShowMessage("Your balance becomes " + newBalance);
}

If the user enter the value 300, the output is:

nazila.hasanzade@hkr.se 3
Last updated 2018 July
Lecture 4

Your project has two classes:

You see that the class Account has two methods: Deposit and ShowMessage

3. Instance variable and Property


Now it is time to extend the class Account with an instance variable and a property. In
previous modules you have declared variables of different data types in the Main method.
Variables can be declared also inside other methods in the same manner as in the Main
method. Variables declared in the body of a method are called local variables. When the
method terminates, the values of the local variables are lost.

In lecture 1 you learned that a class has data or attributes and they are declared at the class
level. Attributes are represented as variables at class level and are called fields. Class level
variables are declared inside a class declaration, but outside any methods of the class.
The instance variables may have public or private access. If the access is public, the variable
can be read or modified outside the object. If the access is private, it can be accessed only
from within the object, by using one of object’s methods or properties (see next paragraph).

Add a field, balance, with access modifier public to the class Account:

public class Account


{
//declare an instance variable that holds the balance
public double balance = 0;

As long as the application runs, this instance variable holds the amount of money you have.
To see how it works, modify the Main method in Accounts:

Console.Write("Enter the first deposit amount: ");


//call myAccount's Deposit method with the read amount as parameter
double newBalance = myAccount.Deposit(double.Parse(Console.ReadLine()));
myAccount.balance = newBalance;

//call myAccount's ShowMessage method with another parameter


myAccount.ShowMessage("Your balance becomes " + myAccount.balance);

//Deposit once again to show how a class level variable works:


Console.Write("Enter the next deposit amount: ");

//call myAccount's Deposit method with the read amount as parameter


newBalance = myAccount.Deposit(double.Parse(Console.ReadLine()));
myAccount.balance = myAccount.balance + newBalance;

nazila.hasanzade@hkr.se 4
Last updated 2018 July
Lecture 4

//call myAccount's ShowMessage method with another parameter


myAccount.ShowMessage("Your balance becomes " + myAccount.balance);

If the users enter 100 and then 200, the output is:

Most instance variables, fields, are private. They are hidden inside the object to respect the
OOP encapsulation principles. Better to let the object itself manipulate its own data. So let’s
change to word public to private before balance. Running the application will now give you:

The application can no longer access this private variable of the object myAccount from the
Main method. The solution is to create a special block of code, called property to read or
modify it:

//property to get or set the balance value

public double Balance


{
get
{
return balance;
}
set
{
balance = value;
}
}

The access modifier is public and it has accessors: get and set, to retrieve and modify data.
The get block contains a return statement: the keyword return followed by an expression.
The set block takes an implicit parameter, value, which passes the new value of the property.
A property can have get or set or both.

Copy and paste the property block into the class Account. Now, go back to the class account
and delete balance and dot operator (.), type a new dot operator and you see the IntelliSense
list:

nazila.hasanzade@hkr.se 5
Last updated 2018 July
Lecture 4

Select Balance from the list and repeat the procedure where needed. Run the application and
notice that you get the same output as before. The difference is that the instance variable,
balance, cannot be accessed outside its object, myAccount. Now you can control the
access to the field balance, by setting conditions in the property block, e.g. adding an if-
statement in the set-block to make sure that the deposit amount is always >0, or by
completely removing the set-accessor, thus allowing the user to only read the balance.

The class diagram looks like:

4. Using constructors to initialize objects


C# does initialize simple data-types to default values as per the language specification in the
.Net framework, but for classes that are user specific, it is obvious that you would be the only
one who can decide what a good default value is. To initialize an object, you use a special
method, called constructor:

public Account()
{
}

A constructor is a method that has the same name as the class name and does not have
any return type as string, double, float, etc. A constructor may take parameters and behave
just like any other method, which means that any instructions can be encapsulated in a
constructor.

public Account (double amount)


{
Balance = amount;
}

A class may have one or many constructors, meaning you may declare many constructors of
the same class that differ only by the types and/or the number of arguments. Remember if you
nazila.hasanzade@hkr.se 6
Last updated 2018 July
Lecture 4

do not declare a constructor the .NET creates one which has no arguments (default
constructor) like: public Account(){}

Now, create a constructor for your class Account, which initializes the balance to an amount
money: existing deposit. Perhaps it could be fetched from a persistent memory (the bank’s
database). In the main class Accounts (that uses objects of the type Account), create and
initialize your account:

//create an Account object and assign it to myAccount


Account myAccount = new Account(200);

Display the balance of the new created object:

//call myAccount's ShowMessage method with another parameter


myAccount.ShowMessage("Your balance is " + myAccount.Balance);

Run the application. The output will be like:

Note: To show date, use the data type DateTime and its property Today:

string dateNOW = Convert.ToString(DateTime.Today);


myAccount.ShowMessage("Your balance is " + dateNOW + " is " + myAccount.Balance);

You can develop the constructor concept to create a more detailed object of the class
Account to contain some more personal data about the owner of the account, like:

public Account(string name, double amount)


{
Name = name;
Balance = amount;
}// end constructor

Of course you have to declare a field ‘name’ and a property ‘Name’. Then create an object:

Account yourAccount = new Account("John Dale", 200);

Do the necessary changes to test the above constructor, and then run the application. If all
works well your output should be:

The class Account now has three constructors. If you add a new method WithDraw, the class
looks like:

nazila.hasanzade@hkr.se 7
Last updated 2018 July
Lecture 4

See the Example code in Canvas under module 3 (Exempelkod). Note that there are some
small changes in the code, for example in the property (set-block) there is an if-statement to
validate the value of balance in order to prevent negative values.

Check the code and read the comments to understand better!

5. More about methods


You have now seen that a class may contain fields (data) and methods. Method is an object-
oriented item of any language. All C# programs are constructed from a number of classes and
almost all the classes will contain methods. A class is like a template and when you instantiate
it, then you will have an object of that class which will match to the real world (like a real
account with an owner name and balance). Object-oriented concepts of programming say that
the data members of each object represent its state and the methods represent the object
behavior. A method is declared as follows:

Return-type methodName ( Parameterslist );

In the class Account you have declared the method Deposit, with return-type double. This
parameter list contains only one parameter. In the class Accounts, wich uses the class
Account, you have created an object

Account myAccount = new Account();

and you have called the method Deposit:

double newBalance = myAccount.Deposit(100);

When the method Deposit is called, the flow of control transfers to this method and the block
of statements are executed. The result is used in other parts of the program.

5.1 Static methods


The method Deposit is executed on its object, myAccount. Sometimes a method of a class
performs a task without referring to a concrete object, but to all objects of this class.
Remember the method Main(). To tell the compiler that this is such a method, the modifier
static is used. Let us look at a simple example that converts the temperature from grade

nazila.hasanzade@hkr.se 8
Last updated 2018 July
Lecture 4

Celsius to grade Fahrenheit. Open a new ConsoleApplication project and add a new class,
ConvertTemp:

public class ConvertTemp


{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);

// Convert Celsius to Fahrenheit.


double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit;
}
}

In the Main() method, use the static metod CelsiusToFahrenheit of this class:

public static void Main(string[] args)


{
double F = 0;

Console.Write(“Please enter the Celsius temperature: “);

// calling the static method by writing name of the class followed by


dot and name of the static method
F = ConvertTemp.CelsiusToFahrenheit(Console.ReadLine());

Console.WriteLine(“Temperature in Fahrenheit: {0:F2}”, F);


}

If we want to convert 40 Celsius grades to Fahrenheit, the output is:

5.2. Passing parameters to methods


In the example ComputeMax from previous lecture you matched the variable names: num1,
num2, num3 in the caller, double maximum = Max(num1, num2, num3);, with the
parameter names in the target method:
// the target method
double Max(double a, double b, double c)

Here is the code:

namespace ComputeMax
{
class Maximum
{
static void Main(string[] args)

nazila.hasanzade@hkr.se 9
Last updated 2018 July
Lecture 4

Console.WriteLine("Enter three numbers\n press 'Enter'


after each one");
double num1 = Convert.ToDouble(Console.ReadLine());
double num2 = Convert.ToDouble(Console.ReadLine());
double num3 = Convert.ToDouble(Console.ReadLine());

double maximum = Max(num1, num2, num3);


Console.WriteLine("The largest number is: " + maximum);
}
public static double Max(double a, double b, double c)
{
double max = a;
if (b > max)
max = b;
if (c > max)
max = c;

return max;
}
}
}

When you call a method, your code must provide values for the method's parameters. By
default the variables are passed to the target method by value. It means that the method
creates its copy of the variable, so when a parameter value is modified inside the method, the
original parameter value outside the method is unchanged. This process is called pass by-
value, and is default in C#.

The behaviour will differ depending on the passed type, so if you are passing a value type
such as int, double, (in this case the value itself will be copied to the method) then the
changes made in the parameter value (the one inside the method) will not affect the variable
value, because it's a separate copy.
Now we discuss only pass by-value and pass by reference of a value type – a simple data type.
As you know, a variable of a value type contains the value itself, and when you assign that
variable to another variable, it will copy its value into the new variable. The same thing
happens when you pass a variable to a method's parameter: the method makes a copy of the
variable's value on its local stack. So the variable and the parameter both refer to separate
copies, and any changes made by the method to its own copy (the method parameter) will not
be reflected to the calling code variable (the argument). This is default, as we said before. See
the following example.

5.2.1 Passing Param By Value

namespace PassingParamByValue
{
public class PassByValue
{
public static void Main()
{
int valueType = 9;
Console.WriteLine("The value of the variable valueType" +
" = {0}", valueType);

ShowNumber(valueType);
Console.WriteLine("After calling the method the value of" +
"the variable valueType = {0}", valueType);
nazila.hasanzade@hkr.se 10
Last updated 2018 July
Lecture 4

Console.WriteLine("The value of the variable valueType after" +


"executing the method ShowNumber = {0}", valueType);

public static void ShowNumber(int x)


{
x++;
Console.WriteLine("Inside the method the parameter x" + " = {0}", x);
}
}
}

The output is;

In the Main method, at first two lines, we assign value 9 to the variable valueType, shown by
printing its value. Next, we call the method ShowNumber and pass the variable to it. The value
increases with 1 and the new value is printed: 10. The method ends and the control is returned
to the Main method. We can then see that the variable is still 9.

Try the example in Visual Studio and check the result!

5.2.2 Passing Param By Reference


Let us try the same example to pass the valueType variable by reference, to see what will
happen. To pass a value type by reference, we need to use the parameter modifier keyword
ref (or out, see output parameters). You must use the ref keyword both in the method
declaration and in method calling. When you use the ref keyword, you actually pass a
reference to the data (the address of the memory location where the data is stored), and there
is no data copying process. Changes made to the method's parameter are stored in the same
location in memory and will be reflected to the calling code variable. Add the ref keyword
before the data type in the method declaration and in the calling code:

namespace PassingParamByReference
{
Public class PassByteReference
{
static void Main()
{
int valueType = 9;
Console.WriteLine("The value of the variable valueType= {0}",
valueType);
ShowNumber(ref valueType);
Console.WriteLine("After calling the method the value of the
variable valueType = {0}", valueType);
}

static void ShowNumber(ref int x)


{
x++;
Console.WriteLine("Inside the method the parameter x = {0}", x);
}
}
}
nazila.hasanzade@hkr.se 11
Last updated 2018 July
Lecture 4

The output is:

Note that the variable has changed its value inside the method ShowNumber and still keeps
the new value outside the method. The variable’s value has been changed.

Try the example in Visual Studio and check the result!

5.3. Output parameters


The out parameter modifier keyword has the same effects as the ref keyword, with one
important difference. With the ref keyword, you must initialize the variable before you pass it
as the method parameters, but with the out keyword you can initialize the variable inside the
method as follows:

public class Program


{

public static void Method(out int i)


{
i = 44;
}

static void Main(string[] args)


{
Console.WriteLine("\tThis method takes an out parameter and returns
nothing \n\tjust assigns the value 44 to the local variable i");
int value;
Console.WriteLine("\tYou call the method: Method(out value),
without passing \n\tany value to its parameter");
Method(out value);
//You don't initialize the parameter when you call the method,
//but you see that the value is now 44
Console.WriteLine("\tThe variable value is now {0}", value);

Console.ReadKey();
}

Try the example in Visual Studio and check the result!

Links: methods
C# Method Parameters
http://www.blackwasp.co.uk/CSharpMethodParameters.aspx

The out Parameter in C#


https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-
modifier
nazila.hasanzade@hkr.se 12
Last updated 2018 July