Beruflich Dokumente
Kultur Dokumente
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
The new object now exists but it has no attributes. You can call its method by using dot
operator (.) as:
objectName.methodName();
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();
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:
//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
nazila.hasanzade@hkr.se 3
Last updated 2018 July
Lecture 4
You see that the class Account has two methods: Deposit and ShowMessage
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:
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:
nazila.hasanzade@hkr.se 4
Last updated 2018 July
Lecture 4
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:
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.
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.
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:
Note: To show date, use the data type DateTime and its property Today:
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:
Of course you have to declare a field ‘name’ and a property ‘Name’. Then create an object:
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.
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
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.
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:
return fahrenheit;
}
}
In the Main() method, use the static metod CelsiusToFahrenheit of this class:
namespace ComputeMax
{
class Maximum
{
static void Main(string[] args)
nazila.hasanzade@hkr.se 9
Last updated 2018 July
Lecture 4
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.
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
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.
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);
}
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.
Console.ReadKey();
}
Links: methods
C# Method Parameters
http://www.blackwasp.co.uk/CSharpMethodParameters.aspx