In the previous chapter we talked about objects and classes without writing a single line of code: the class is the blueprint and the object is what you build from it. Understanding the idea is fine, but it only really sinks in when you write one and see what happens.
Today you write your first class. We will model a product in a corner store, and that same Product class will stay with us for the rest of this part.
Your first class
A corner store product has a name and a price. Here is that as a class:
var coffee = new Product();
coffee.Name = "Coffee";
coffee.Price = 3.50m;
var bread = new Product();
bread.Name = "Bread";
bread.Price = 1.25m;
Console.WriteLine($"{coffee.Name}: {coffee.Price:0.00}");
Console.WriteLine($"{bread.Name}: {bread.Price:0.00}");
class Product
{
public string Name = "";
public decimal Price;
}
Coffee: 3.50
Bread: 1.25
Three new things here:
class Product { ... }defines the blueprint. Inside you declare the data every product will have.new Product()builds an object from the blueprint. Eachnewcreates a different object with its own data.coffee.Nameuses the dot to reach into the object and read or change one of its pieces of data.
coffee and bread are two objects of the same class. Changing the price of one does not touch the other.
Look at where the class sits: after the program’s statements. In Program.cs, the code that runs goes on top and type declarations (classes, and later interfaces) go below. If you put a class before the statements, the compiler tells you top-level statements must precede type declarations (error CS8803). Later in this chapter we see the normal way to organize it, one file per class.
Fields and properties
Name and Price in the example above are fields: variables declared inside the class. They work, but anyone can set them to anything from the outside. To control that, C# has properties:
var coffee = new Product { Name = "Coffee", Price = 3.50m };
Console.WriteLine($"{coffee.Name} costs {coffee.Price:0.00}");
coffee.Price = 4.00m;
Console.WriteLine($"{coffee.Name} costs {coffee.Price:0.00}");
class Product
{
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Coffee costs 3.50
Coffee costs 4.00
A property is declared with { get; set; }: get is the door to read the value and set is the door to change it. C# creates the field behind the scenes. From the outside you use it like a field, but now you can decide which doors stay open:
{ get; set; }: can be read and changed from outside.{ get; private set; }: can be read from outside, but only changed from inside the class.{ get; init; }: can be read, and is only assigned when the object is created. After that it is fixed.
If Price were { get; private set; } and you wrote coffee.Price = 10m; from the program, it would not compile (error CS0272). With init, a coffee.Name = "Other"; after creating the object does not compile either (error CS8852). That is the point: the object decides how its data changes.
The = "" at the end of Name gives it an initial value so that string is never really empty (null); the project has Nullable turned on and the compiler warns you if you forget. Property names use PascalCase, like functions.
The syntax new Product { Name = "Coffee", Price = 3.50m } is called an object initializer: you build and assign in one step. It works with properties that can be assigned from the outside.
Constructors
A product without a name makes no sense, and with an object initializer nothing forces you to give one. The fix is a constructor: a block that runs when you do new and receives what the object needs to exist.
var coffee = new Product("Coffee", 3.50m);
var bread = new Product("Bread", 1.25m);
Console.WriteLine($"{coffee.Name}: {coffee.Price:0.00}");
Console.WriteLine($"{bread.Name}: {bread.Price:0.00}");
class Product
{
public string Name { get; init; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
}
Coffee: 3.50
Bread: 1.25
The constructor has the same name as the class and no return type, not even void. Now new Product() with no arguments no longer compiles: to create a product you must say its name and price. Since the constructor assigns Name and Price, we no longer need the = "" either: the compiler sees they are never left without a value.
Methods on the object
In chapter 6 you wrote functions. When a function lives inside a class and works with the object’s data, it is called a method. The difference from what you wrote before is that these do not have static: you call them on a specific object.
var coffee = new Product("Coffee", 3.50m);
Console.WriteLine($"Before: {coffee.Price:0.00}");
coffee.ApplyDiscount(10);
Console.WriteLine($"After: {coffee.Price:0.00}");
class Product
{
public string Name { get; init; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
public void ApplyDiscount(decimal percent)
{
Price = Price - Price * percent / 100;
}
}
Before: 3.50
After: 3.15
ApplyDiscount changes Price, something the main program cannot do directly because the set is private. The data and what you can do with it live together in the same class. That is what chapter 8 called encapsulation, and in the next chapter we use it to protect the object from nonsense values.
this
Inside a method, Price means “the price of this object”. C# has a word for that “this”: this. The line above could be written like this, with the same result:
this.Price = this.Price - this.Price * percent / 100;
When you call coffee.ApplyDiscount(10), this is coffee. If you call bread.ApplyDiscount(10), this is bread. You normally do not need to write it. You will mostly see it in constructors that store a parameter in a field with the same name, like this.price = price;, to tell the field from the parameter.
Objects are references
With an int, int b = a; copies the value: afterwards you have two independent numbers. With an object, var b = a; copies the reference: a and b point to the same object. This fragment uses the Product class from the previous section:
var a = new Product("Coffee", 3.50m);
var b = a;
var c = new Product("Coffee", 3.50m);
b.ApplyDiscount(10);
Console.WriteLine($"a: {a.Price:0.00}");
Console.WriteLine($"b: {b.Price:0.00}");
Console.WriteLine($"c: {c.Price:0.00}");
Console.WriteLine(a == b);
Console.WriteLine(a == c);
a: 3.15
b: 3.15
c: 3.50
True
False
We applied the discount to b, and a changed too, because they are the same object with two names. c was built with the same data but it is a different object, so it did not change, and a == c gives False. For classes, == asks “are they the same object?”, not “do they have the same data?”.
This matters when you pass an object to a method: the method receives the reference, and if it changes the object, the caller sees the change.
ToString: how an object is displayed
If you print an object directly, C# does not know how to show it (again with the earlier Product class, without ToString):
var coffee = new Product("Coffee", 3.50m);
Console.WriteLine(coffee);
Product
It prints the class name. Every object in C# has a ToString() method that Console.WriteLine uses to turn it into text, and by default it returns the type name. You can replace it with your own version:
var coffee = new Product("Coffee", 3.50m);
var bread = new Product("Bread", 1.25m);
coffee.ApplyDiscount(10);
Console.WriteLine(coffee);
Console.WriteLine(bread);
class Product
{
public string Name { get; init; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
public void ApplyDiscount(decimal percent)
{
Price = Price - Price * percent / 100;
}
public override string ToString() => $"{Name}: {Price:0.00}";
}
Coffee: 3.15
Bread: 1.25
The word override means “I replace the method that comes from the base class”. In the next chapter we see why it works that way. For now, it is how you tell C# how to display your object. The arrow => is a short way to write a method that only returns an expression: it is the same as { return $"{Name}: {Price:0.00}"; }.
static: what belongs to the class
So far everything belonged to an object: each product has its own name and price. Sometimes something belongs to the whole class. That is static:
var coffee = new Product("Coffee", 3.50m);
var bread = new Product("Bread", 1.25m);
Console.WriteLine($"{coffee.Name} and {bread.Name}: {Product.Created} products created");
class Product
{
public static int Created { get; private set; }
public string Name { get; init; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
Created++;
}
}
Coffee and Bread: 2 products created
Created exists only once, no matter how many products there are, and you use it with the class name: Product.Created, not coffee.Created. You have already used static members without knowing it: int.TryParse, Math.Max and Console.WriteLine are called on the type, not on an object. new List<string>(), on the other hand, creates an object, and Add is called on that object.
Watch out for the double meaning. The static from chapter 6, on a local function, meant “this function does not see the outside variables”. The static on a class member means “it belongs to the class, not to an object”. The practical rule: if the data or the method depends on one particular product, it is not static.
One file per class
Keeping everything in Program.cs is fine for learning, but in a real project each class lives in its own file. Create Product.cs next to Program.cs and move the class there, without changing a line:
class Product
{
public string Name { get; init; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
}
Program.cs is left with just the statements. The compiler reads every file in the project, so new Product(...) keeps working. That avoids the problem of putting the class before the statements, and you find each class by its file name. From here on, if you prefer to work this way, do it.
Mini-exercise: stock in the store
Extend Product so it tracks inventory:
- Add a
Stockproperty of typeint, readable from outside and changeable only from inside the class. The constructor must receive the initial stock. - Add the methods
Sell(int quantity), which subtracts from the stock, andRestock(int quantity), which adds. - Change
ToString()so it shows the stock, for exampleBread: 1.25 (25 in stock). - Test it: create a
Breadat 1.25 with 20 in stock, sell 5, restock 10 and print it.
Suggested solution
var bread = new Product("Bread", 1.25m, 20);
bread.Sell(5);
bread.Restock(10);
Console.WriteLine(bread);
class Product
{
public string Name { get; init; }
public decimal Price { get; private set; }
public int Stock { get; private set; }
public Product(string name, decimal price, int stock)
{
Name = name;
Price = price;
Stock = stock;
}
public void ApplyDiscount(decimal percent)
{
Price = Price - Price * percent / 100;
}
public void Sell(int quantity)
{
Stock -= quantity;
}
public void Restock(int quantity)
{
Stock += quantity;
}
public override string ToString() => $"{Name}: {Price:0.00} ({Stock} in stock)";
}
Bread: 1.25 (25 in stock)
20 minus 5 plus 10 is 25. Now try bread.Sell(100): the stock ends up at -80 and nobody complains. Nothing prevents a negative price either. The class protects who changes the data, but it does not yet protect which values it accepts. That is what we fix in the next chapter.
What you learned
- A
classis the blueprint;newbuilds an object with its own data. - Fields are variables of the class. Properties (
{ get; set; },{ get; private set; },{ get; init; }) control who reads and who changes each piece of data. - The constructor has the class name and forces you to supply the data needed to create the object.
- A method is a function inside the class, and
thisis the object it was called on. - Objects are references:
var b = a;does not copy the object, it creates another name for the same one. ToString()says how an object is displayed, andstaticmarks what belongs to the class rather than to an object.
In the next chapter we make Product reject invalid values, and see how classes relate to each other: encapsulation, inheritance, polymorphism and interfaces.
Stuck?
If a class does not compile or you do not understand why an object changed when you did not expect it, DM me on Instagram or ask in the Discord community. Paste your code and the error you get, and we will work through it.
