Video: Using Classes and Objects in C# (Bulgarian)
June 14, 2022
Nikolay Kostov (Nikolay.IT)
Topics covered:
Classes and Objects
What are Objects?
What are Classes?
Classes in C#
Declaring Class
Fields and Properties: Instance and Static
Instance and Static Methods
Constructors
Enumerations
Structures
Namespaces
Random class
Introduction to .NET Common Type System
Video (in Bulgarian)
Presentation Content
What are Objects?
Software objects model real-world objects or abstract concepts
Examples:
bank, account, customer, dog, bicycle, queue
Real-world objects have states and behaviors
Account’ states:
holder, balance, type
Account’ behaviors:
withdraw, deposit, suspend
How do software objects implement real-world objects?
Use variables/data to implement states
Use methods/functions to implement behaviors
An object is a software bundle of variables and related methods
Classes
Classes act as templates from which an instance of an object is created at run time. Classes define the properties of the object and the methods used to control the object’s behavior.
Classes provide the structure for objects
Define their prototype, act as template
Classes define:
Set of attributes
Represented by variables and properties
Hold their state
Set of actions ( behavior )
Represented by methods
A class defines the methods and types of data associated with an object
Objects
An object is a concrete instance of a particular class
Creating an object from a class is called instantiation
Objects have state
Set of values associated to their attributes
Example:
Class: Account
Objects: Ivan’s account, Peter’s account
Classes in C#
Classes – basic units that compose programs
Implementation is encapsulated (hidden)
Classes in C# can contain:
Fields (member variables)
Properties
Methods
Constructors
Inner types
Etc. (events, indexers, operators, …)
Classes in C# – Examples
Example of classes (structures):
System.Console
System.String ( string in C#)
System.Int32 ( int in C#)
System.Array
System.Math
System.Random
System.DateTime
System.Collections.Generics.List<T>
Fields
Fields are data members of a class
Can be variables and constants (read-only)
Accessing a field doesn’t invoke any actions of the object
Just accesses its value
Example:
String.Empty (the “” string)
Properties
Properties look like fields
Have name and type
Can contain code, executed when accessed
Usually used as wrappers
To control the access to the data fields
Can contain more complex logic
Can have two components called accessors
get for reading their value
set for changing their value
According to the implemented accessors properties can be:
Read-only ( get accessor only)
Read and write (both get and set accessors)
Write-only ( set accessor only)
Example of read-only property:
String.Length
Example of read-write property:
Console.BackgroundColor
Instance and Static Members
Fields, properties and methods can be:
Instance (or object members)
Static (or class members)
Instance members are specific for each object
Example: different dogs have different name
Static members are common for all instances of a class
Example: DateTime.MinValue is shared between all instances of DateTime
Accessing Members – Syntax
Accessing instance members
The name of the instance , followed by the name of the member (field or property), separated by dot (" . ")
Accessing static members
The name of the class , followed by the name of the member
Instance and Static Members – Examples
Example of instance member
String.Length
Each string object has a different length
E.g. “I like C#”.Length 9
Example of static member
Console.ReadLine()
The console is only one (global for the program)
Reading from the console does not require to create an instance of it
Methods
Methods manipulate the data of the object to which they belong or perform other tasks
Examples:
Console.WriteLine(…)
Console.ReadLine()
String.Substring(index, length)
Array.GetLength(index)
List<T>.Add(item)
DateTime.AddDays(count)
Instance Methods
_Instance methods _ manipulate the data of a specified object or perform any other tasks
If a value is returned, it depends on the particular class instance
Syntax:
The name of the instance, followed by the name of the method, separated by dot
Static Methods
_Static methods _ are common for all instances of a class (shared between all instances)
Returned value depends only on the passed parameters
No particular class instance is available
Syntax:
The name of the class, followed by the name of the method, separated by dot
Constructors
Constructors are special methods used to assign initial values of the fields in an object
Executed when an object of a given type is being created
Have the same name as the class that holds them
Do not return a value
A class may have several constructors with different set of parameters
Constructor is invoked by the new operator
Parameterless Constructors
The constructor without parameters is called _default _ ( parameterless ) constructor
Example:
Creating an object for generating random numbers with a default seed
Enumerations
Enumerations in C# are types whose values are limited to a predefined set of values
E.g. the days of week
Declared by the keyword enum in C#
Hold values from a predefined set
Structures
Structures in C# are similar to classes
Structures are _value _ types (directly hold a value)
Classes are reference types (pointers)
Structures are usually used for storing data structures, without any other functionality
Structures can have fields, properties, etc.
Using methods is not recommended
Example of structure
System.DateTime – represents a date and time
What is a Namespace?
Namespaces are used to organize the source code into more logical and manageable way
Namespaces can contain
Definitions of classes, structures, interfaces and other types and other namespaces
Namespaces can contain other namespaces
For example:
System namespace contains Data namespace
The name of the nested namespace is System.Data
Full Class Names
A full name of a class is the name of the class preceded by the name of its namespace
Example:
Array class, defined in the System namespace
The full name of the class is System.Array
<namespace_name>.<class_name>
Password Generator – Example
Write a program to generate a random password between 8 and 15 characters
The password contains of at least two capital letters, two small letters, one digit and three special characters
Constructing the password generator class:
Start from an empty password
Place 2 random capital letters at random positions
Place 2 random small letters at random positions
Place 1 random digit at random positions
Place 3 special characters at random positions
Now we have exactly 8 characters
To make the password length between 8 and 15 we add between 0 and 7 random characters
Capital / small letters / digits / special character
Inserts each of them at random position
Common Type System (CTS)
CTS defines all datatypes supported in .NET Framework
Primitive types (e.g. int , float , object )
Classes (e.g. String , Console , Array )
Structures (e.g. DateTime )
Arrays (e.g. int[] , string[,] )
Etc.
Object-oriented by design
CTS and Different Languages
CTS is common for all .NET languages
C#, VB.NET, J#, JScript.NET, ...
CTS type mappings:
CTS Type
C# Type
VB.NET Type
System.Int32
int
Integer
System.Single
float
Single
System.Boolean
bool
Boolean
System.String
string
String
System.Object
object
Object
System.Object: CTS Base Type
System.Object ( object in C#) is a base type for all other types in CTS
Can hold values of any other type:
All .NET types derive common methods from System.Object , e.g. ToString()
Value and Reference Types
In CTS there are two categories of types
Value _ _ types
Reference types
Placed in different areas of memory
Value types live in the _execution _ stack*
Freed when become out of scope
Reference types live in the _managed heap _ (dynamic memory)
Freed by the _garbage _ collector
_* _ Note: this _ does not mean _ that _ value types, which are part of reference types _ live on the stack. E.g., integers in a List<int> _ do not _ live on the stack
Value and Reference Types – Examples
Value types
Most of the primitive types
Structures
Examples: int , float , bool , DateTime
Reference types
Classes and interfaces
Strings
Arrays
Examples: string , Random , object , int[]
Summary
Classes provide the structure for objects
Objects are particular instances of classes
Classes have different members
Methods, fields, properties, etc.
Instance and static members
Members can be accessed
Methods can be called
Structures are used for storing data
Namespaces group related classes
Namespaces help organizing the classes
Common Type System (CTS) defines the types for all .NET languages