INTRODUCTION TO CLASSES &
OBJECTS
CREATING CLASSES USING C#
OBJECTS VS CLASSES
• Classes are abstract definitions of what an object can do and values it can hold
• Classes are a mix of code and data
• An object is an instance of a class
• Classes are general and Objects are specific examples
DATA HIDING
• Class data is private
• Protected from unsafe manipulation
• Modified only by class specific methods
• Methods may be public or private
• Private methods for internal class use only
• Public methods are defined interface to the class’ data
DECLARING THE DATA
class Die
{
private int _sides;
private int _value;
Variables declared
as private
Variables are declared private
Variable names start with underscore (_) to highlight that they are private (optional)
CONSTRUCTORS
• Constructors are methods in a class that set the initial state of an object
• Constructors:
•
•
•
•
Are public
Have the same name as the class
Do not have a specified type
Initialize private values in a class
SAMPLE CONSTRUCTORS
public Die()
{
_sides = 6;
ChangeValue();
}
public Die(int sides)
{
_sides = sides;
ChangeValue();
}
Default constructor
No parameter
Default value for
number of sides
Non default constructor
Parameter(s)
Number of sides set to value
passed to the constructor
ACCESSING THE DATA
• Class data should be accessed using methods or properties
• Changes to data should be validated carefully inside the class if allowed
at all
• Some data should not be allowed to be changed after the constructor
CHANGING DATA - METHOD
private void ChangeValue()
{
_value = r.Next(0, _sides) + 1;
}
Declared private
Used only in the class
Code to set value is
“hidden”
RETURNING DATA - METHOD
public int Roll()
{
ChangeValue();
return _value;
}
_value changed in
a private method
_value returned
by method not by
direct access
GETTING/SETTING DATA - PROPERTY
public int Value
_value returned
by method not by
{
direct access
get { return _value; }
set {
if (value > 0 && value < _sides+1)
_value = value; }
}
_value set in a
protected fashion
DECLARING AN OBJECT
Die dSix = new Die();
Die d12 = new Die(12);
Default constructor
Six sides are default
Non default specifies
the number of sides
REVIEW
• An instance of a class is an object
• One or more constructors to set initial values
• Constructors have the same name as the class
• Access to data is limited and protected
© Copyright 2026 Paperzz