0% found this document useful (0 votes)
16 views15 pages

C# Class Properties and Constructors

This document covers key concepts in object-oriented programming using C#, specifically focusing on class properties and constructors. It explains how to define class-scoped variables, access properties of instantiated objects, and the significance of constructors for initializing object states. The document also includes 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)
16 views15 pages

C# Class Properties and Constructors

This document covers key concepts in object-oriented programming using C#, specifically focusing on class properties and constructors. It explains how to define class-scoped variables, access properties of instantiated objects, and the significance of constructors for initializing object states. The document also includes 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

CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

UNIT 4 C# CLASS PROPERTIES

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Adding State
3.2 Defining a Class-Scoped Variable
3.3 Accessing Properties of Instantiated Objects
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

This unit expands upon the previous creation of simple classes by


introducing class properties. Properties of a class allow instantiated
objects to have a state with each object controlling its own data. Enjoy
your studies.

2.0 OBJECTIVES

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

• Define a class-scoped variable


• State the syntax for adding two integer variables to the Rectangle
class to hold the height and width
• Explain how to access properties of Instantiated Objects

106
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

3.0 MAIN CONTENT

3.1 Adding State

In the previous unit, you learnt about the basic syntax and process of
creating a class that has methods as a part of its public interface. This
allows the generation of simple classes with behaviour but without state.

However, the state of an object is the property which describes its


individual data or unique configuration. In the example of a car object,
methods allow us to accelerate or decelerate but the state, described in
properties, allows us to determine the actual speed and to describe one
car object as red and another as blue. This information creates a real
differentiation between the two objects.

SELF ASSESSMENT EXERCISE

Which property describes the unique configuration of an object?

3.2 Defining a Class-Scoped Variable

In many cases, the information that is made public via a property is held
directly within the object as a variable. This variable has a scope that
makes it visible to the entire class. This is not always the case however,
as the information may be held in a database or other external source or
may be calculated rather than stored. In the class example in this unit, two
of the property values will be held in variables and two will be
calculated.

To define a class-scoped variable, the declaration is made within the


class' code block but outside of any methods or properties. Although not
required, it is useful to precede the variable declaration with the private
keyword to make the code clear and easy to read. Using this syntax, we
can add two integer variables to the Rectangle class to hold the height
and width.

class Rectangle
{

107
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

private int _width;


private int _height;
}

NB: The use of lower camel case and an underscore (_) prefix is one
naming standard for class-level variables. It is a useful, though not
essential, convention.

3.3 Accessing Properties of Instantiated Objects

Properties of instantiated objects are accessed using the object name


followed by the member access operator (.) and the property name. The
property can be read from and written to using similar syntax as for a
standard variable. To demonstrate this, consider the following example
code, added to the Main method of the program. It creates two objects
based upon the Rectangle class and assigns and reads their properties
individually. When trying to assign an invalid height to a rectangle, an
exception is thrown by the validation code.

static void Main(string[] args)


{
Rectangle rect = new Rectangle();
[Link] = 50;
[Link] = 25;

Rectangle square = new Rectangle();


[Link] = [Link] = 40;

[Link]([Link]); // Outputs "25"


[Link]([Link]); // Outputs "40"

[Link] = 25; // Throws the validation exception.


}

NB: The sample code demonstrates both encapsulation and state. The
state of the two rectangles is held internally and independently and the
implementation details of the properties are hidden from the program. If,
in the future, we need to move the data from the private variables into an
XML file or database, the Main method will not need to be changed.

108
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

4.0 CONCLUSION

To wrap up, recall that the state of an object is the property which
describes its individual data or unique configuration. A class-scoped
variable is defined by making a declaration within the class' code block
but outside of any methods or properties. Properties of instantiated
objects are accessed using the object name followed by the member
access operator (.) and the property name.

5.0 SUMMARY

This unit provided an overview of class properties, illustrating how to


define class-scoped variables and access properties of instantiated
objects. However, to assess your level of assimilation , you would need
to attempt the questions below.

6.0 TUTOR MARKED ASSIGNMENT

 Define a class-scoped variable


 Describe how to access properties of instantiated objects

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.
[Link] 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.

109
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.
[Link]
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.

110
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

MODULE 3 C# CONSTRUCTORS AND DESTRUCTORS

Unit 1 Constructors
Unit 2 Default Constructor
Unit 3 Destructors
Unit 4 Garbage Collection

UNIT 1 CONSTRUCTORS

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Significance of Constructors
3.2 What is a Constructor?
3.3 Creating a New Class
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

This unit examines constructors. These special methods allow objects to


be initialised on instantiation and to perform final actions before they are
removed from memory. Enjoy your studies.

2.0 OBJECTIVES

What you would study in this unit, would enable you:

• Identify the main significance of constructors


• Give a brief description of constructors
• Create a new class

111
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

3.0 MAIN CONTENT

3.1 Significance of Constructors

To set properties in Classes, an object is instantiated and the property


values are assigned individually. This gives the desired result but is not
ideal as it is possible for a property to be forgotten and left undefined,
possibly leaving the entire object in an invalid state. This problem is
solved with the use of constructors by initialising all the public and
private state of the object.

SELF ASSESSMENT EXERCISE

What is the main function of a constructor?

3.2 What is a Constructor?

A constructor is a special class member that is executed when a new


object is created. The constructor's job is to initialise all of the public
and private state of the new object and to perform any other tasks that
the programmer requires before the object is used.

3.3 Creating a New Class

In this unit, we will create a new class to represent a triangular shape.


This class will define three properties: the triangle's height, base-length
and area. To begin, create a new console application and add a class
named "Triangle". Copy and paste the following code into the class to
create the three properties that are required.

public class Triangle


{
private int _height;

112
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

private int _baseLength;

public int Height


{
get
{
return _height;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}

_height = value;
}
}

public int BaseLength


{
get
{
return _baseLength;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}

_baseLength = value;
}
}

public double Area


{
get
{
return _height * _baseLength * 0.5;
}
}
}

113
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

4.0 CONCLUSION

Winding up, we can go over the key points of this unit. A constructor is
a special class member that is executed when a new object is created.
The main function of the constructor is to initialise all of the public and
private state of the new object and to perform any other tasks that the
programmer requires before the object is used. To create a new class to
represent a triangular shape that will define three properties: the
triangle's height, base-length and area. First, create a new console
application and add a class named "Triangle". Then key in the required
appropriate code into the class to create the three properties that are
required.

5.0 SUMMARY

This unit provided an overview of constructors, their key role and


procedure for creating a class of a new object to define some properties.
We hope you have found this unit interesting.

6.0 TUTOR MARKED ASSIGNMENT

 What is a constructor?
 Outline the procedure involved in creating a new class to
represent a rectangular shape that will define the rectangle’s
length, width and area

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.
[Link] 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)

114
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

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.
[Link]
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.

115
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

UNIT 2 THE DEFAULT CONSTRUCTOR

CONTENTS

1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is a Default Constructor?
3.2 Replacing the Default Constructor
3.2.1 Syntax for Adding a New Constructor to a Class
3.2.2 Maintaining the Valid Range of the Sides of a
Triangle
3.3 Executing the Constructor
4.0 Conclusion
5.0 Summary
6.0 Tutor Marked Assignment
7.0 References/Further Readings

1.0 INTRODUCTION

This unit gives a general idea of the default constructor. It equally states
the syntax for adding a new constructor to a class and gives the
description of how the constructor is executed. Enjoy your studies.

2.0 OBJECTIVES

What you would study in this unit, would equip you to do the following:

• Describe the default constructor


• State the Syntax for adding a new constructor to a class
• Give the code for maintaining the valid range of the sides of a
triangle (class)
• Describe how to execute the constructor

3.1 What is a Default Constructor?

A default constructor is simply the constructor that is applied in a class if


no other constructor is explicitly declared by the developer. This
constructor causes all of the value type properties and variables to be set
to zero and all reference types to be set to null. If these are invalid
values for an object, as in the Triangle class above, the default

116
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

constructor will always create an object that is invalid. In this case, the
default constructor should be replaced.

SELF ASSESSMENT EXERCISE

When is a default constructors applied in a class?

3.2 Replacing the Default Constructor


3.2.1 Syntax for Adding a New Constructor to a Class

The syntax to add a new constructor to a class is similar to that of adding


a method. However, the constructor has the same name as the class and
does not include a return type. The declaration for the Triangle's new
constructor is therefore simply:

public Triangle()

3.2.2 Maintaining the Valid Range of the Sides of a Triangle

To ensure that all triangles will have a height and base-length within the
valid range, we will make the class' constructor set both of these
properties to one unit for all new Triangle objects. This is achieved by
simply setting the underlying private variables in the constructor's code
block. Add the following code within the class' code block to add the
constructor.

public Triangle()
{
[Link]("Triangle constructor executed");

_height = _baseLength = 1;
}

NB: The [Link] command is added to show that the


constructor has been executed in the examples. This would generally not
be added to a real class definition.

3.3 Executing the Constructor

The newly added constructor replaces the default constructor and is


executed automatically when a new Triangle is instantiated. This can be

117
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

tested by adding some code to the console application's Main method.


Add the following code and execute the program to test the results and
to see that the height and base-length are set correctly.

static void Main(string[] args)


{
Triangle triangle = new Triangle();

[Link]("Height:\t{0}", [Link]);
[Link]("Base:\t{0}", [Link]);
[Link]("Area:\t{0}", [Link]);
}

/* OUTPUT

Triangle constructor executed


Height: 1
Base: 1
Area: 0.5

*/

4.0 CONCLUSION

To end, a default constructor is simply the constructor that is applied in


a class if no other constructor is explicitly declared by the developer. We
also identified. Ensure that all classes, say triangles, have a height and
base-length within the valid range, by simply setting the underlying
private variables in the constructor's code block.

5.0 SUMMARY

This unit provided an overview of the default constructor. It equally


stated the syntax for adding a new constructor to a class and explained
how the constructor is executed. We hope you found this unit
enlightening.

6.0 TUTOR MARKED ASSIGNMENT

118
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

• Give the code for maintaining the valid range of the sides of a
triangle (class)
• Describe how to execute the constructor

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.
[Link] 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.
[Link]
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.

119
CIT 834 OBJECT-ORIENTED PROGRAMMING USING C#

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.

120

Common questions

Powered by AI

Improper use of class properties can lead to challenges such as leaving critical properties uninitialized, resulting in objects being in an invalid or inconsistent state. This can cause runtime errors or unpredictable behavior in the program. Constructors help mitigate these issues by ensuring that objects are fully initialized with valid and logical state information upon creation, reducing the likelihood of properties being forgotten or set incorrectly .

To implement a new class in C#, the process typically starts with defining private variables that hold the internal state of the class. These variables ensure encapsulation by safeguarding sensitive data and logic. Next, public properties are created to provide controlled access to these private variables, allowing operations such as validation and logging within property accessors. Lastly, a custom constructor is added to initialize the class state properly, enabling the setting of initial values that are critical for the object’s functionality. Each of these components plays a crucial role: private variables protect the inner workings, public properties enable interaction with the class while preserving stability, and a custom constructor provides a mechanism to ensure all initialized objects meet necessary preconditions .

Constructors in object-oriented programming are special methods used to initialize objects when they are instantiated. They ensure that all necessary initial states and dependencies of an object are properly set, preventing the object from being created in an invalid state. This reduces the chances of runtime errors due to uninitialized fields and enhances the robustness and reliability of the class structure .

Replacing default constructors with custom constructors in the Triangle class ensures that all instances of the class begin in a valid state. By explicitly setting fields such as '_height' and '_baseLength' to one unit, the custom constructor prevents the creation of Triangle objects with invalid dimensions, as would have been possible with a default constructor that sets these fields to zero. This ensures that every Triangle object starts with a minimum valid configuration, thus enhancing reliability and preventing errors during execution .

The concept of encapsulation is demonstrated in the Rectangle class example by keeping the state of the rectangle (i.e., width and height) private and allowing access to these properties only through public getters and setters. This hides the internal implementation details and protects the integrity of the data by ensuring that access to the class internals is controlled and validated, as demonstrated by the validation exception when an invalid value is assigned to the height . It is important because it ensures that the object's state can only be altered in well-defined ways, thereby promoting data integrity and security .

To access a property of an instantiated object in C#, first reference the object by name, followed by the member access operator (a period), and then the property name. For example, given an instance of a Rectangle object named 'rect', the height can be accessed as 'rect.Height'. This syntax allows for both reading and writing to the property, provided it is not read-only or write-only .

Member access operators (the dot operator) are significant in object-oriented programming because they provide a straightforward syntax for interacting with an object's properties and methods. In C#, this operator delineates the relationship between an object instance and its members, allowing programmers to read, write, or invoke methods on the object's members efficiently. This centralized access method enhances readability and clarity by showing direct context and hierarchy in the code, thus making it easier to manage complex interactions within object-oriented applications .

Default constructors are automatically provided by C# if no constructors are explicitly defined. They initialize all value type properties to zero and reference types to null. Parameterized constructors, on the other hand, allow for specific initialization by passing arguments to the constructor, providing more control over the initial state of an object. Default constructors are useful when a simple default state is sufficient, while parameterized constructors should be used when the object requires specific initial values to function correctly or when certain fields must be initialized to prevent invalid states .

Using private variables to back properties in a class is significant as it enforces encapsulation by restricting direct access to the class state from outside the class. Instead, the state is accessed and modified through controlled property accessors, allowing for data validation and the application of logic whenever the state changes. This design improves the maintainability and robustness of the class by permitting changes to internal implementation without affecting external code that uses the class .

Class-scoped variables have a scope that makes them accessible throughout the class, allowing for the storage of data that multiple methods or properties might need to access. They contribute to maintaining the state of an object, thus affecting the overall structure of a program by reducing redundancy and facilitating data encapsulation. By using class-scoped variables, programmers can ensure that updates to related data are localized within the class, simplifying maintenance and reducing the likelihood of errors in the program logic .

You might also like