creating-the-classes-slides
creating-the-classes-slides
Gill Cleeren
CTO Xpirit Belgium
@gillcleeren
Overview
Creating the Product class
Using composition
Working with class-level members
Splitting into multiple partial classes
Creating the Product class
The Class Template
protected and
public internal
private
Can I leave out the
access modifier?
internal by default
Id
Name
Description
Maximum in stock
Price & currency
Unit type
Current amount in stock
Low on stock?
public class Product
{
private int id;
private string name = string.Empty;
}
private public
protected internal
Using encapsulation
Change and access through public
interface
“Use” product
Add new product to inventory
Alert if low on stock
Display the details of a product (short & long)
Adding a Method
Public if part of the public interface
Can work with private fields to change state of object they belong to
The Method Template
Adding methods
Using “getter and setter” Methods
Using a Property
Combination of private field and public method
Contain get and set accessors
Can contain logic to check value
Analyzing a Full Property
Product.cs Product.cs
Adding properties
Using properties inside the class
Creating Objects
Adding a Constructor
Used to instantiate an object with initial values
Numeric to 0
Char to ‘\0’
Boolean to false
References to null
What happens if we
omit the constructor?
A default constructor is created for
us
Adding constructors
Do we always need to
find unique names?
Combination of parameters (number,
order, data types) must be unique
Method overloading
public void IncreaseStock()
{
AmountInStock++;
}
“this”
Copy of fields
Methods
Properties Copy of fields
Copy of fields
public Product(int id, string name)
{
this.Id = id;
this.Name = name;
}
Primary Constructors
Introduced in C# 12
Way of declaring a constructor whose parameters are available in body of the type
public class Product(int id, string name)
{
public Product(int id, string name, decimal price)
: this(id, name)
{ }
}
Product
Price
Using Composition
Product.cs Product2.cs