0% found this document useful (0 votes)
15 views19 pages

Week 2

This document covers the fundamentals of C# classes in object-oriented programming, including class definitions, instance variables, and methods. It outlines the syntax for creating classes, the use of the dot operator, and the process of adding and instantiating classes in C#. The document also provides objectives, self-assessment exercises, and references for further reading.

Uploaded by

bioabiola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views19 pages

Week 2

This document covers the fundamentals of C# classes in object-oriented programming, including class definitions, instance variables, and methods. It outlines the syntax for creating classes, the use of the dot operator, and the process of adding and instantiating classes in C#. The document also provides objectives, self-assessment exercises, and references for further reading.

Uploaded by

bioabiola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

MODULE 2 C# CLASS

Unit 1 Preamble to C# Class


Unit 2 Operation on C# Class
Unit 3 Adding Methods
Unit 4 C# Class Properties

UNIT 1 PREAMBLE TO C# CLASS

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Class Fundamentals
3.1.1 Class Description
3.1.2 General Form of a Class
3.1.3 General Form of an Instance Variable
3.1.4 General Form of a Dot Operator
3.1.5 Class Definition Syntax
3.1.6 Simple C# Class
3.2 Creating a C# Class
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

Classes are at the heart of every object-oriented language. With classes,


as with a lot of the language's features, C# borrows a little from C++ and
Java and adds some ingenuity to create elegant solutions to old
problems. In this unit, we'll equally give a brief description of classes in
C#.

2.0 OBJECTIVES

At the end of this unit, you should be able to:

87
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

• Describe a class
• Give the general form of a class
• Declare an instance variable
• State the general form of a dot operator
• State the class definition syntax
• Outline the procedure for creating a simple C# class

3.0 MAIN CONTENT

3.2 Class Fundamentals

The class is the basic building block of code when creating object-
oriented software. It describes in abstract all of the characteristics and
behaviour of a type of object. Once instantiated, an object is generated
that has all of the methods, properties and other behaviour defined
within the class.

Consequently a class should not be confused with an object. The class is


the abstract concept for an object that is created at design-time by the
programmer. While objects based upon the class are the concrete
instances of the class that occur at run-time. For example, the Car class
will define that all cars have a make, model and colour. Only at run-time
will an object be instantiated as a Red.

3.1.1 Class Description

A class is can simply be described as a template that defines the form of


an object. It specifies both the data and the code that will operate on that
data. Methods and variables that constitute a class are called members of
the class.

3.1.2 General Form of a Class

A class is created by use of the keyword class.


The general form of a class definition that contains only instance variables and

methods is given as:


class classname {
// declare instance variables
access type var1;
access type var2;
// ...

88
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

access type varN;

// declare methods
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}

3.1.3 Declaring Instance Variable

The general form for declaring an instance variable is shown here:


access type var-name;
An instance variable consists of the following:
1. access which specifies the access,
2. type which specifies the type of variable, and
3. var-name which is the variable's name.

In order to access these variables, you will use the dot (.) operator.
The dot operator links the name of an object with the name of a member.

3.1.4 General Form of a Dot Operator

The general form of the dot operator is shown here:

Object.member

The dot operator is used to access both instance variables and methods.

3.1.5 Class Definition Syntax

Class definition syntax is given as:

89
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

class MyClass
{
int simpleValue = 0;
}

3.1.6 Simple C# Class

A simple C# class is given as:


using System;

class MainClass {
MainClass() {
Console.WriteLine("MainClass Constructor Called");
}

~MainClass() {
Console.WriteLine("MainClass Destructor Called");
}
void PrintAMessage(string msg) {
Console.WriteLine("PrintAMessage: {0}", msg);
}
void Dispose() {
GC.SuppressFinalize(this);
}

static void Main() {


Console.WriteLine("Top of function main");
MainClass app = new MainClass();
app.PrintAMessage("Hello from class");
Console.WriteLine("Bottom of function main");
app.Dispose();
}
}

90
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

SELF ASSESSMENT EXERCISE

State the class definition syntax

3.2 Creating a Class

Now that we have had an overview of classes, we would consider the


syntax for the creation of a new class. The basic syntax for the creation
of a new class is very simple. The keyword 'class' followed by the name
of the new class is simply added to the program. This is then followed by
a code block surrounded by brace characters {} to which the class' code
will be added.

class class-name {}

4.0 CONCLUSION

We discovered that the class is the basic building block of code when
creating object-oriented software. It describes in abstract all of the
characteristics and behaviour of a type of object. We equally saw the
syntax for a simple class creation as well as the general form of a dot
operator.

5.0 SUMMARY

In this unit, we learnt about the general form of a class, instance variable
declaration general form of a dot operator as well as the procedure for
creating a simple C# class. Be assured that the facts gathered from this
unit will be valuable for building C# applications. OK! Let us attempt
the questions below.

6.0 TUTOR MARKED ASSIGNMENT

 Give a brief description of a class


 State the general form of a dot operator

91
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

7.0 REFERENCES/FURTHER READINGS

1. Abelson, H and Gerald J. S. (1997). Structure and Interpretation


of Computer Programs. The MIT Press.
2. Armstrong, Deborah J. (2006). "The Quarks of Object-Oriented
Development". Communications of the ACM 49 (2): 123–128.
http://portal.acm.org/citation.cfm?id=1113040. Retrieved 2006-
08-08.
3. Booch, Grady (1997). Object-Oriented Analysis and Design with
Applications. Addison-Wesley.
4. Date, C. J and Hugh, D. (2006). Foundation for Future Database
Systems: The Third Manifesto (2nd Edition)
5. Date, C. J and Hugh, D. (2007). Introduction to Database
Systems: The Sixth Manifesto (6th Edition)
6. Eeles, P and Oliver, S. (1998). Building Business Objects. John
Wiley & Sons.
7. Gamma, Erich; Richard Helm, Ralph Johnson, John Vlissides
(1995). Design Patterns: Elements of Reusable Object Oriented
Software. Addison-Wesley.
8. Harmon, Paul; William Morrissey (1996). The Object Technology
Casebook - Lessons from Award-Winning Business Applications.
John Wiley & Sons.
9. Jacobson, Ivar (1992). Object-Oriented Software Engineering: A
Use Case-Driven Approach. Addison-Wesley.
10. John C. Mitchell, Concepts in programming languages,
Cambridge University Press, 2003, p.278
11. Kay, Alan. The Early History of Smalltalk.
http://gagne.homedns.org/%7etgagne/contrib/EarlyHistoryST.ht
ml.
12. Martin, A and Luca, C. (2005). A Theory of Objects.
13. Meyer, Bertrand (1997). Object-Oriented Software Construction.
Prentice Hall.
14. Michael Lee Scott (2006). Programming language pragmatics,
(2nd Edition) p. 470
15. Pierce, Benjamin (2002). Types and Programming Languages.
MIT Press.
16. Rumbaugh, James; Michael Blaha, William Premerlani,
Frederick Eddy, William Lorensen (1991). Object-Oriented
Modeling and Design. Prentice Hall.
17. Schreiner, A. (1993). Object oriented programming with ANSI-C.
18. Taylor, David A. (1992). Object-Oriented Information Systems -
Planning and Implementation. John Wiley & Sons.
19. Trofimov, M. (1993) OOOP - The Third "O" Solution: Open
OOP. First Class, OMG, Vol. 3, issue 3, p.14.

92
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

UNIT 2 OPERATIONS ON A CLASS

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Adding a C# Class
3.1.1 Adding a C# Class using a Solution Explorer
3.1.2 Adding a C# Class in Class View
3.2 Instantiating a Class
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

C# Classes can be added by two main methods, these are by using:


(1) The Solution Explorer or (2) The Class View. This unit sheds more
light on this.

2.0 OBJECTIVES

At the end of this unit, you should be able to:

• Identify 2 main methods of adding C# Classes


• Enumerate the steps involved in adding a C# Class using Solution
Explorer
• Outline the procedure for adding a C# Class in Class View
• Describe how to instantiate a Class

3.0 MAIN CONTENT

3.1 Adding a C# Class

We can add C# Classes to applications in two main ways, these are by:

93
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

a. Adding a C# Class using Solution Explorer


b. Adding a C# Class in Class View

We would look at the procedure for accomplishing these tasks in


the proceeding units.

3.1.1 Adding a C# Class Using Solution Explorer

You can build a generic class that is automatically declared under the
current default namespace. For example, classes added to a project
named WindowsApplication1 are added to the namespace
WindowsApplication1.
Adding a class in Solution Explorer

1. In Solution Explorer, right-click the project name and click Add,


and then click Add Class.
The Add New Item dialog box appears with the C# Class icon
already selected.

2. In the dialog box, enter a class name in the Name field and click
Open.
The new class is added to your project.

3.1.2 Adding a C# Class Using Class View

When you add a class from Class View, you have maximum control defining
elements while using C# Class Wizard.
To add a class in Class View

• In Class View, right-click the project name and click Add


• Then click Add Class
• The C# Class Wizard appears

94
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

SELF ASSESSMENT EXERCISE

Outline the procedure for adding a C# Class using Class View

3.2 Instantiating a Class

Although we have not explicitly added any functionality to the class, it


can now be instantiated to create objects. These objects will have the
standard behaviour of all classes. To demonstrate this, return to the
program code file containing the Main method. In this method we will
create a new vehicle object and run its ToString method to see the
results. As we have not yet defined how ToString should work, this will
simply show the fully qualified name.

static void Main(string[] args)


{
Vehicle car = new Vehicle();
Console.WriteLine(car.ToString()); // Outputs "ClassTest.Vehicle"
}

NB: The prefix of ClassTest is simply the name of the namespace of the
Vehicle class.

4.0 CONCLUSION

Classes are added in C# either by employing the class view or solution


explorer.

5.0 SUMMARY

In summary, this unit looked at two main methods of adding C# Classes.


We equally identified the procedure for instantiating Classes. We can
now attempt the questions below.

95
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

6.0 TUTOR MARKED ASSIGNMENT

Outline the procedure for accomplishing the following tasks:

1. Adding a C# class in solution explorer


2. Adding a C# class in class view
3. Instantiating a C# class

7.0 REFERENCES/FURTHER READINGS

1. Abelson, H and Gerald J. S. (1997). Structure and Interpretation


of Computer Programs. The MIT Press.
2. Armstrong, Deborah J. (2006). "The Quarks of Object-Oriented
Development". Communications of the ACM 49 (2): 123–128.
http://portal.acm.org/citation.cfm?id=1113040. Retrieved 2006-
08-08.
3. Booch, Grady (1997). Object-Oriented Analysis and Design with
Applications. Addison-Wesley.
4. Date, C. J and Hugh, D. (2006). Foundation for Future Database
Systems: The Third Manifesto (2nd Edition)
5. Date, C. J and Hugh, D. (2007). Introduction to Database
Systems: The Sixth Manifesto (6th Edition)
6. Eeles, P and Oliver, S. (1998). Building Business Objects. John
Wiley & Sons.
7. Gamma, Erich; Richard Helm, Ralph Johnson, John Vlissides
(1995). Design Patterns: Elements of Reusable Object Oriented
Software. Addison-Wesley.
8. Harmon, Paul; William Morrissey (1996). The Object Technology
Casebook - Lessons from Award-Winning Business Applications.
John Wiley & Sons.
9. Jacobson, Ivar (1992). Object-Oriented Software Engineering: A
Use Case-Driven Approach. Addison-Wesley.
10. John C. Mitchell, Concepts in programming languages,
Cambridge University Press, 2003, p.278
11. Kay, Alan. The Early History of Smalltalk.
http://gagne.homedns.org/%7etgagne/contrib/EarlyHistoryST.ht
ml.
12. Martin, A and Luca, C. (2005). A Theory of Objects.
13. Meyer, Bertrand (1997). Object-Oriented Software Construction.
Prentice Hall.

96
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

14. Michael Lee Scott (2006). Programming language pragmatics,


(2nd Edition) p. 470
15. Pierce, Benjamin (2002). Types and Programming Languages.
MIT Press.
16. Rumbaugh, James; Michael Blaha, William Premerlani,
Frederick Eddy, William Lorensen (1991). Object-Oriented
Modeling and Design. Prentice Hall.
17. Schreiner, A. (1993). Object oriented programming with ANSI-C.
18. Taylor, David A. (1992). Object-Oriented Information Systems -
Planning and Implementation. John Wiley & Sons.
19. Trofimov, M. (1993) OOOP - The Third "O" Solution: Open
OOP. First Class, OMG, Vol. 3, issue 3, p.14.

97
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

UNIT 3 C# METHODS

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Methods
3.1.1 Declaring Methods
3.1.2 Calling a Method
3.2 Method Parameters
3.3 Creating a Reference Type
3.4 Return Values
3.5 Public Methods
3.6 Private Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

In C# every executed instruction is done in the context of a method.


We’ll be considering methods, how they are called and declared as well
the two common methods.

2.0 OBJECTIVES

At the end of this unit, you should be able to:


• Describe a Method
• Identify how Methods are declared
• Explain the concept of Method Parameters
• State the syntax for declaring a Reference type

98
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

3.0 MAIN CONTENT

3.1 Methods

A method is a code block containing a series of statements. In C#, every


executed instruction is done in the context of a method.

3.1.1 Declaring Methods

Methods are declared within a class or struct by specifying the access


level, the return value, the name of the method, and any method
parameters. Method parameters are surrounded by parentheses, and
separated by commas. Empty parentheses indicate that the method
requires no parameters. This class contains three methods:

class Motorcycle
{
public void StartEngine() { }
public void AddGas(int gallons) { }
public int Drive(int miles, int speed) { return 0; }
}

3.1.2 Calling a Method

Calling a method on an object is similar to accessing a field. After the


object name; add a period, the name of the method, and parentheses.
Arguments are listed within the parentheses, and separated by commas.
The methods of the Motorcycle class can therefore be called like this:

Motorcycle moto = new Motorcycle();

moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);

99
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

SELF ASSESSMENT EXERCISE

How are Methods declared?

3.2 Method Parameters

Passing arguments to a method is simply a matter of providing them in


the parentheses when calling a method. To the method being called, the
incoming arguments are called parameters.
The parameters a method receives are also provided in a set of
parentheses, but the type and a name for each parameter must be
specified. The name does not have to be the same as the argument. For
example:

public static void PassesInteger()


{
int fortyFour = 44;
TakesInteger(fortyFour);
}
static void TakesInteger(int i)
{
i = 33;
}
Here a method called PassesInteger passes an argument to a method
called TakesInteger. Within PassesInteger, the argument is named
fortyFour, but in TakeInteger, this is a parameter named i. This
parameter exists only within the TakesInteger method. Any number of
other variables can be named i, and they can be of any type, so long as
they are not parameters or variables declared inside this method.
Notice that TakesInteger assigns a new value to the provided argument.
One might expect this change to be reflected in the PassesInteger
method once TakeInteger returns, but in fact the value in the variable
fortyFour remains unchanged. This is because int is a value type. By
default, when a value type is passed to a method, a copy is passed
instead of the object itself. Because they are copies, any changes made
to the parameter have no effect within the calling method. Value types
get their name from the fact that a copy of the object is passed instead of
the object itself. The value is passed, but not the same object.

100
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

This differs from reference types, which are passed by reference. When
an object based on a reference type is passed to a method, no copy of the
object is made. Instead, a reference to the object being used as a method
argument is made and passed. Changes made through this reference will
therefore be reflected in the calling method.

3.3 Creating a Reference Type

A reference type is created with the class keyword, like this:

public class SampleRefType


{
public int value;
}

Now, if an object based on this type is passed to a method, it will be


passed by reference. For example:

public static void TestRefType()


{
SampleRefType rt = new SampleRefType();
rt.value = 44; ModifyObject(rt);
System.Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
obj.value = 33;
}
This example essentially does the same thing as the previous example.
But, because a reference type is used, the modification made by
ModifyObject is made to the object created in the TestRefType method.
The TestRefType method will therefore display the value 33.

3.4 Return Values

Methods can return a value to the caller. If the return type, the type listed
before the method name, is not void, then the method can return the
value using the return keyword. A statement with the keyword return
followed by a value that matches the return type will return that value to
the method caller. The return keyword also stops the execution

101
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

of the method. If the return type is void, a return statement with no


value is still useful to stop the execution of the method. Without the
return keyword, the method will stop executing when it reaches the end
of the code block. Methods with a non-void return type are required to
use the return keyword to return a value. For example, these two
methods use the return keyword to return integers:

class SimpleMath
{
public int AddTwoNumbers(int number1, int number2)
{
return number1 + number2;
}

public int SquareANumber(int number)


{
return number * number;
}
}

To use a value returned from a method, the calling method can use the
method call itself anywhere a value of the same type would suffice. You
can also assign the return value to a variable. For example, the following
two code examples accomplish the same goal:

int result = obj.AddTwoNumbers(1, 2);


obj.SquareANumber(result);

obj.SquareANumber(obj.AddTwoNumbers(1, 2));
Using an intermediate variable, in this case, result, to store a value is
optional. It may help the readability of the code, or it may be necessary
if the value is going to be used more than once.

3.5 Public Methods

Public methods are part of the class' public interface. Essentially, they
are the methods that can be called by other objects.

The syntax for creating methods described previously must be modified


slightly to make the methods visible to external objects. To achieve this,
the public keyword is used as a prefix. The following code added to the
vehicle class provides a new method for pressing a vehicle's horn. Make
sure that you add the code within the class' code block.

102
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

public void PressHorn()


{
Console.WriteLine("Toot toot!");
}

To use the new method, change the code within the Main method as
follows:

static void Main(string[] args)


{
Vehicle car = new Vehicle();
car.PressHorn(); // Outputs "Toot toot!"
}

3.6 Private Methods

To provide for encapsulation, where the internal functionality of the


class is hidden, some methods will be defined as Private. Methods with
a private protection level are completely invisible to external classes.
This makes it safe for the code to be modified to change functionality,
improve performance, etc. without the need to update classes that use
the public interface. To define a method as private, the private keyword
can be used as a prefix to the method. Alternatively, using no prefix at
all implies that the method is private by default.

The following method of the car class is a part of the internal


implementation not the public interface so is defined as being private.

private void MonitorOilTemperature()


{
// Internal oil temperature monitoring code...;
}

To demonstrate that this method is unavailable to external classes, try


the following code in the Main method of the program. When you
attempt to compile or execute the program, an error occurs indicating
that the MonitorOilTemperature method cannot be called due to its
protection level.

static void Main(string[] args)


{
Vehicle car = new Vehicle();
car.MonitorOilTemperature();

103
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

4.0 CONCLUSION

In conclusion, Methods are codes of blocks containing series of


statements. They are declared within a class or struct by specifying the
access level, the return value, the name of the method, and any method
parameters. Methods can either be Public or Private.

5.0 SUMMARY

In this unit, we described methods and identified the syntax for


declaring and calling methods. We equally considered the concept of
method parameters and reference types. Hope you grasped the key
points. Now, let us attempt the questions below.

6.0 TUTOR MARKED ASSIGNMENT

• Explain how methods are declared


• State the syntax for declaring a Reference Type

7.0 REFERENCES/FURTHER READINGS

1. Abelson, H and Gerald J. S. (1997). Structure and Interpretation


of Computer Programs. The MIT Press.
2. Armstrong, Deborah J. (2006). "The Quarks of Object-Oriented
Development". Communications of the ACM 49 (2): 123–128.
http://portal.acm.org/citation.cfm?id=1113040. Retrieved 2006-
08-08.
3. Booch, Grady (1997). Object-Oriented Analysis and Design with
Applications. Addison-Wesley.
4. Date, C. J and Hugh, D. (2006). Foundation for Future Database
Systems: The Third Manifesto (2nd Edition)
5. Date, C. J and Hugh, D. (2007). Introduction to Database
Systems: The Sixth Manifesto (6th Edition)
6. Eeles, P and Oliver, S. (1998). Building Business Objects. John
Wiley & Sons.
7. Gamma, Erich; Richard Helm, Ralph Johnson, John Vlissides
(1995). Design Patterns: Elements of Reusable Object Oriented
Software. Addison-Wesley.

104
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

8. Harmon, Paul; William Morrissey (1996). The Object Technology


Casebook - Lessons from Award-Winning Business Applications.
John Wiley & Sons.
9. Jacobson, Ivar (1992). Object-Oriented Software Engineering: A
Use Case-Driven Approach. Addison-Wesley.
10. John C. Mitchell, Concepts in programming languages,
Cambridge University Press, 2003, p.278
11. Kay, Alan. The Early History of Smalltalk.
http://gagne.homedns.org/%7etgagne/contrib/EarlyHistoryST.ht
ml.
12. Martin, A and Luca, C. (2005). A Theory of Objects.
13. Meyer, Bertrand (1997). Object-Oriented Software Construction.
Prentice Hall.
14. Michael Lee Scott (2006). Programming language pragmatics,
(2nd Edition) p. 470
15. Pierce, Benjamin (2002). Types and Programming Languages.
MIT Press.
16. Rumbaugh, James; Michael Blaha, William Premerlani,
Frederick Eddy, William Lorensen (1991). Object-Oriented
Modeling and Design. Prentice Hall.
17. Schreiner, A. (1993). Object oriented programming with ANSI-C.
18. Taylor, David A. (1992). Object-Oriented Information Systems -
Planning and Implementation. John Wiley & Sons.
19. Trofimov, M. (1993) OOOP - The Third "O" Solution: Open
OOP. First Class, OMG, Vol. 3, issue 3, p.14.

105

You might also like