.NET e la programmazione orientata agli oggetti.
A cura di Nicholas Magi — nicholas.magi[at]ispascalcomandini.it

Anders Heijlsberg, Ingegnere software danese

Write once, run anywhere.
Architettura della JVM
Codice Java (viene compilato in)$\rightarrow$ Bytecode (viene eseguito da)$\rightarrow$ JVM
Stessa filosofia, per più linguaggi.

Architettura del CLR
Codice C# (viene compilato in)$\rightarrow$ CIL (viene eseguito da)$\rightarrow$ CLR
Le implementazioni sono allineate e unificate a .NET.
$\downarrow$
Attenzione alla syntactic sugar!


Da https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types
.sln (o .slnx).csproj<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Library</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MyProject.Core\MyProject.Core.csproj" />
</ItemGroup>
</Project>
Esempio del contenuto di un file progetto (.csproj)

Esempio su GitHub: https://github.com/dotnet/samples/tree/main/framework/libraries/migrate-library-csproj
src/ inseriamo il codice sorgente della nostra applicazione (possono essere previsti più progetti sotto src/)tests/ specchia la stessa gerarchia dei file e delle cartelle di src/
pippo, pluto, f(x)…PascalCase per nomi di classi, metodi, proprietà, interfacce, namespacecamelCase per le variabiliUPPER_CASE_SNAKE_CASE per le costanti(prima degli anni ‘50)
(anni ‘50 - ‘60)
(anni ‘70 - ‘80)
(anni ‘90 - ‘2000)
Machine Lang / Assembly / C portano ad una visione molto hardware-oriented di un problema
Nel tempo nasce la necessità di modellare le entità che costituiscono un dominio applicativo, e delle varie relazioni tra di loro - minimizzando le risorse (tempo, fatica…) dedicate alla gestione di aspetti non inerenti alla risoluzione del problema.
Necessità di ASTRAZIONE!
#01. Everything is an object. Un oggetto è una entità che fornisce operazioni per essere manipolata.
#02. Un programma è un set di oggetti che si comunicano cosa fare scambiandosi messaggi. Questi messaggi sono richieste per eseguire le operazioni fornite.
#03. Un oggetto ha una memoria fatta di altri oggetti. Un oggetto è ottenuto impacchettando altri oggetti.
#04. Ogni oggetto è istanza di una classe. Una classe descrive il comportamento dei suoi oggetti.
#05. Tutti gli oggetti di una classe possono ricevere gli stessi messaggi. La classe indica tra le altre cose quali operazioni sono fornite, quindi per comunicare con un oggetto basta sapere qual è la sua classe.
Rappresentazione UML
Unified Modelling Language

Codice, pt. 1/2
namespace BlaisePascal.OOPExamples.Domain;
enum State { ON, OFF }
public class Bulb
{
// "Memoria" dell'oggetto
int _brightness;
State _state;
// Costruttore
public Bulb()
{
this._brightness = 0;
this._state = State.OFF;
}
// Metodi
public void On()
{
this._brightness = 100;
this._state = State.ON;
}
public void Off()
{
this._brightness = 0;
this._state = State.OFF;
}
// [...]
Codice, pt. 2/2
// [...]
public void Dim()
{
if (this._brightness - 1 < 0)
{
this.Off();
return;
}
this._brightness--;
}
public void Brighten()
{
if (this._brightness + 1 > 100)
{
this.On();
return;
}
this._brightness++;
}
}
1namespace BlaisePascal.OOPExamples.Domain;
2
3public class ComplexNumber
4{
5 public int Real { get; set; }
6 public int Imaginary { get; set; }
7
8 public ComplexNumber(int re, int im)
9 {
10 this.Real = re;
11 this.Imaginary = im;
12 }
13
14 public ComplexNumber Add(ComplexNumber other)
15 {
16 return new ComplexNumber(
17 this.Real + other.Real,
18 this.Imaginary + other.Imaginary
19 );
20 }
21
22 public ComplexNumber Subtract(ComplexNumber other)
23 {
24 return this.Add(new ComplexNumber(
25 -other.Real,
26 -other.Imaginary
27 ));
28 }
29
30 public ComplexNumber Multiply(ComplexNumber other)
31 {
32 // Formula: (a + ib)*(c * id) = (ac - bd) + (ad + bc)*i
33 int a = this.Real; int b = this.Imaginary;
34 int c = other.Real; int d = other.Imaginary;
35 return new ComplexNumber(a*c - b*d, a*d + b*c);
36 } // [...]
37}
(Cosa vede chi utilizza la libreria)
1namespace BlaisePascal.OOPExamples.Domain.UnitTests;
2
3public class ComplexNumberTest
4{
5 [Fact]
6 public void Constructor_SetsRealAndImaginary()
7 {
8 // Arrange
9 var complex = new ComplexNumber(2, 3);
10 // Act & Assert
11 Assert.Equal(2, complex.Real);
12 Assert.Equal(3, complex.Imaginary);
13 }
14
15 [Fact]
16 public void Add_ReturnsSumOfRealAndImaginary()
17 {
18 // Arrange
19 var c1 = new ComplexNumber(1, 2);
20 var c2 = new ComplexNumber(3, 4);
21
22 // Act
23 var result = c1.Add(c2);
24
25 // Assert
26 Assert.Equal(4, result.Real);
27 Assert.Equal(6, result.Imaginary);
28 }
29
30 [Fact]
31 // [...]
32}
1namespace BlaisePascal.OOPExamples.Domain;
2
3enum State { ON, OFF }
4
5public class Bulb
6{
7 // "Memoria" dell'oggetto
8 int _brightness;
9 State _state;
10
11 // Costruttore
12 public Bulb()
13 {
14 this._brightness = 0;
15 this._state = State.OFF;
16 }
17
18 // Metodi
19 public void On()
20 {
21 this._brightness = 100;
22 this._state = State.ON;
23 }
24
25 public void Off()
26 {
27 this._brightness = 0;
28 this._state = State.OFF;
29 }
30
31 // [...]
32}
(Cosa vede chi utilizza la libreria)
1namespace BlaisePascal.OOPExamples.Presentation;
2
3using BlaisePascal.OOPExamples.Domain;
4
5public class UseBulb
6{
7 public static void Main(string[] args)
8 {
9 Bulb newBulb = new Bulb();
10 Console.WriteLine("New bulb created!");
11
12 Console.WriteLine(
13 "Initial brightness: " + newBulb._brightness
14 ); // ERRORE!
15 Console.WriteLine(
16 "Initial state: " + newBulb._state
17 ); // ERRORE!
18
19 for (int i = 0; i < 3; i++)
20 {
21 newBulb.Brighten();
22 }
23 // Here, 'brightness' should be equal to 3 -
24 // we could use xunit to make a unit test
25 // and assert that ;)
26
27 newBulb.On();
28 // [...]
29 }
30}

Paradigma orientato al problem solving, prendendo le distanze da dettagli irrilevanti della macchina utilizzata.
Posso (io, progettista) nascondere in una classe informazioni che non voglio rendere visibili all’esterno (altri, utilizzatori).
Proprietà e metodi possono essere ereditati di classe in classe, sovrascritti oppure estesi.
Lo stesso metodo o la stessa proprietà può assumere comportamenti diversi a seconda dello scenario.
// ...” commento su una linea/* ... */” commento su più linee - utilizzato per commentare sezioni interne del codice/// <summary> ... </summary>” commenti di documentazione, da posizionare sopra classi e membri pubblici del codice
int x, y, z; !Tree”, “Graph”, “Car”, “Person”…IEquatable<>”, “IComparer”, “ICollection”…Point3D / 1namespace BlaisePascal.OOPExamples.Domain;
/// <summary>
/// Point3D is an example showcasing some functionality of OO in C#, focussing
/// on formatting. All properties have default - private - access.
/// </summary>
public class Point3D
{
static readonly Point3D ZERO = new Point3D(0, 0, 0);
/*
A Point3D is made of three fields and has some manipulation functions.
*/
double _x;
double _y;
double _z;
/// <summary>
/// Constructor of Point3D class.
/// </summary>
public Point3D(double x, double y, double z)
{
this._x = x;
this._y = y;
this._z = z;
}
// [...]
Point3D / 2 /// <summary>
/// Calculates the squared module of the point, i.e. (x**2) + (y**2) + (z**2).
/// </summary>
public double GetSquareModule()
{
return this._x * this._x + this._y * this._y + this._z * this._z;
}
/// <summary>
/// Apply translation to point in three axes.
/// </summary>
public void Translate(double x, double y, double z)
{
this._x += x;
this._y += y;
this._z += z;
}
/// <summary>
/// Static method to calculate the point with maximum squared module.
/// </summary>
public static Point3D Max(Point3D[] points)
{
var max = ZERO;
foreach (var point in points)
{
if (point.GetSquareModule() > ZERO.GetSquareModule())
{
max = point;
}
}
return max;
}
}
“Dividi e conquista”, approccio top-down.
la soluzione di un problema complesso avviene dividendolo in problemi più semplici, tra loro indipendenti.
suddivisione in namespace (simili ai package di altri linguaggi, tipo Java o Kotlin)
suddivisione in classi (all’interno di un namespace)
suddivisione in metodi (all’interno di una classe)
Counterpublic class Counter
{
// Utilizzo property: sintetizza in una riga
// - dichiarazione di un field
// - dichiarazione di un get pubblico default
// - dichiarazione di un set privato
public int Count { get; private set; }
public Counter()
{
this.Count = 0;
}
public void Increment()
{
this.Count += 1;
}
}
namespace BlaisePascal.OOPExamples.Presentation;
using BlaisePascal.OOPExamples.Domain;
public class Program
{
public static void UseCounter(Counter counter)
{
int incrementTimes = 4;
Console.WriteLine(counter.Count); // Should be "0"
for (int i = 0; i < incrementTimes; i++)
{
counter.Increment(); // +1 x 4
}
Console.WriteLine(counter.Count); // Should be "4"
}
public static void Main(string[] args)
{
var myCounter = new Counter();
UseCounter(myCounter);
}
}
public class CounterTest
{
private static void CountInArray(int[] array, int target, Counter counter)
{
foreach (var item in array)
{
if (item == target)
{
counter.Increment();
}
}
}
[Fact]
public void Increment_ShouldIncrementCountValueWhenCalledOnArrayCount()
{
// Arrange
var counter = new Counter();
var sampleArray = new int[] { 10, 15, 10, 30, 75, 40 };
var target = 10;
var want = 2;
// Act
CountInArray(sampleArray, target, counter);
var have = counter.Count;
// Assert
Assert.Equal(want, have);
}
[Fact]
public void Increment_ShouldIncrementCountValueWhenCalledOnMatrixCount()
{
// Arrange
var counter = new Counter();
var sampleMatrix = new int[][] {
new int[] { 10, 80, 90 },
new int[] { 10, 10, 65 },
new int[] { 10, 20, 10 },
};
var target = 10;
var want = 5;
// Act
foreach (var array in sampleMatrix)
{
CountInArray(array, target, counter);
}
var have = counter.Count;
// Assert
Assert.Equal(want, have);
}
}
Counter mi impedisce di modificare accidentalmente il valore di Count!
Count è incapsulata dentro alla classe, che è l’unica che ha possibilità di modifica (utilizzando il modificatore di accessibilità private)Count += 1” oppure “counter.increment()”?
increment e non altrove....OnArrayCount() e ...OnMatrixCount())Calculator
Circle, Square, Triangle
Student, Professor, Class
Di cosa stiamo parlando?
Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes.
Studente eredita da Persona: cosa comporta?Da “Microsoft Learn”: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/inheritance

virtual/override, upcasting, downcastingSi progetti in C# un software per il calcolo delle retribuzioni mensili di un’azienda per ciascun impiegato. Ciascun impiegato ha un ID, un nome, un cognome e un dipartimento di afferenza (Human Resources, Accountability, Management…)
Sono previsti diversi tipi di impiegati:
namespace BlaisePascal.OOPExamples.Domain.SalaryCalculator.NOInheritance;
public enum EmployeeType { Hourly, Salaried, CommissionSalaried, Manager, Executive }
public class EmployeeRecord
{
public int Id { get; init; }
public string FullName { get; init; } = string.Empty;
public string Department { get; init; } = string.Empty;
public EmployeeType Type { get; init; }
// Campi specifici orari
public decimal HourlyRate { get; init; }
public double HoursWorked { get; set; }
// Campi specifici stipendiati / manager
public decimal MonthlySalary { get; init; }
// Campi specifici commerciali
public decimal GrossSales { get; set; }
public decimal CommissionRate { get; init; }
// Campi specifici manager
public decimal TargetBonus { get; init; }
public double ObjectiveCompletionRate { get; set; }
// Campi specifici executive
public int StockSharesGranted { get; init; }
public decimal ShareMarketPrice { get; init; }
// [...]
// [...]
public decimal CalculatePay()
{
switch (Type)
{
case EmployeeType.Hourly:
if (HoursWorked <= 160.0)
return (decimal)HoursWorked * HourlyRate;
decimal baseHoursPay = 160.0m * HourlyRate;
decimal overtimePay = (decimal)(HoursWorked - 160.0) * (HourlyRate * 1.5m);
return baseHoursPay + overtimePay;
case EmployeeType.Salaried:
return MonthlySalary;
case EmployeeType.CommissionSalaried:
return MonthlySalary + (GrossSales * CommissionRate);
case EmployeeType.Manager:
return MonthlySalary + (TargetBonus * (decimal)ObjectiveCompletionRate);
case EmployeeType.Executive:
decimal managerPart = MonthlySalary + (TargetBonus * (decimal)ObjectiveCompletionRate);
decimal equityPart = StockSharesGranted * ShareMarketPrice;
return managerPart + equityPart;
default:
throw new InvalidOperationException("Tipo non supportato.");
}
}
// [...]
// [...]
public string GetDetails()
{
string header = $"[{Id}] {FullName} - Dip. {Department}";
switch (Type)
{
case EmployeeType.Hourly:
return $"{header} | Orario ({HoursWorked}h a {HourlyRate:C}/h)";
case EmployeeType.Salaried:
return $"{header} | Fisso: {MonthlySalary:C}";
case EmployeeType.CommissionSalaried:
return $"{header} | Fisso: {MonthlySalary:C} + Provvigione ({CommissionRate:P0} su {GrossSales:C})";
case EmployeeType.Manager:
return $"{header} | Fisso: {MonthlySalary:C} + Bonus ({TargetBonus:C} al {ObjectiveCompletionRate:P0})";
case EmployeeType.Executive:
return $"{header} | Fisso: {MonthlySalary:C} + Bonus ({TargetBonus:C} al {ObjectiveCompletionRate:P0}) + Equity: {StockSharesGranted} az. ({ShareMarketPrice:C})";
default:
return header;
}
}
Due grossi problemi:
Non stiamo usando i princìpi fondamentali della OOP!
Osserviamo che, per ciascun dipendente, si presentano delle caratteristiche comuni:
Ciascun dipendente, inoltre, ha una funzionalità CalculateMonthlyPay() - la cui implementazione cambia a seconda del tipo di dipendente.
Potremmo quindi pensare di creare una classe padre Employee che raccolga le caratteristiche a fattor comune, ma che lasci la libertà a ciascuna specializzazione di calcolare lo stipendio secondo le sue modalità.
1namespace BlaisePascal.OOPExamples.Domain.SalaryCalculator.WithInheritance;
2
3public abstract class Employee
4{
5 public int Id { get; private set }
6 public string FullName { get; private set }
7 public string Department { get; private set }
8
9 protected Employee(int id, string fullName, string department)
10 {
11 Id = id;
12 FullName = fullName;
13 Department = department;
14 }
15
16 // Contratto: ogni sottoclasse concreta deve implementare la formula
17 public abstract decimal CalculateMonthlyPay();
18
19 // Metodo estendibile: fornisce l'intestazione comune
20 public virtual string GetEmploymentDetails()
21 {
22 return $"[{Id}] {FullName} - Dip. {Department}";
23 }
24}
1namespace BlaisePascal.OOPExamples.Domain.SalaryCalculator.WithInheritance;
2
3public class HourlyEmployee : Employee
4{
5 private readonly decimal EXTRA = 1.5m;
6 public decimal HourlyRate { get; init; }
7 public double HoursWorked { get; set; }
8
9 public HourlyEmployee(int id, string fullName, string department, decimal hourlyRate, double hoursWorked)
10 : base(id, fullName, department)
11 {
12 HourlyRate = hourlyRate;
13 HoursWorked = hoursWorked;
14 }
15
16 public override decimal CalculateMonthlyPay()
17 {
18 const double standardHours = 160.0;
19 if (HoursWorked <= standardHours)
20 return (decimal)HoursWorked * HourlyRate;
21
22 decimal standardPay = 160.0m * HourlyRate;
23 decimal overtimePay = (decimal)(HoursWorked - standardHours) * (HourlyRate * EXTRA);
24 return standardPay + overtimePay;
25 }
26
27 public override string GetEmploymentDetails() =>
28 $"{base.GetEmploymentDetails()} | Orario ({HoursWorked}h a {HourlyRate:C}/h)";
29}
namespace BlaisePascal.OOPExamples.Domain.SalaryCalculator.WithInheritance;
public class SalariedEmployee : Employee
{
public decimal MonthlySalary { get; init; }
public SalariedEmployee(int id, string fullName, string department, decimal monthlySalary)
: base(id, fullName, department)
{
MonthlySalary = monthlySalary;
}
public override decimal CalculateMonthlyPay() => MonthlySalary;
public override string GetEmploymentDetails() =>
$"{base.GetEmploymentDetails()} | Fisso: {MonthlySalary:C}";
}
// ESERCIZIO: Continuare l’implementazione seguendo il tracciato.
Con la parola chiave abstract si può contrassegnare una classe in cui non tutto è implementato
abstract DEVONO fornire una loro implementazione, mediante l’uso di override.E cosa vuol dire virtual?
override).int CalculateAge(Date birthday);)int, bool, string, ecc…)
DomusController con riutilizzo del codice?
// TODO
Object.Equals()IEquatable<T>, IComparerLanguage-INtegrated Query
Functional programming is a way of thinking about software construction by creating pure functions. It avoids concepts of shared state and mutable data observed in Object Oriented Programming.
Functional languages emphasize expressions and declarations rather than the execution of statements. Therefore, unlike other procedures which depend on a local or global state, value output in FP depends only on the arguments passed to the function.
— da Guru99.com, https://www.guru99.com/functional-programming-tutorial.html
int sum(x, y)
{
return x + y;
}
// Inizializza una variabile 'x' a 0
int x = 0;
// Crea una **nuova** variabile 'x'
// con il valore aggiornato
x = x + 1;
(supponendo di lavorare in un linguaggio basato sul paradigma funzionale)
for o while!int Fibonacci(int n)
{
return n >= 1 ?
Fibonacci(n-1) + Fibonacci(n-2) :
1;
}
Teoria matematica preponderante e molto rigorosa.

Concetto identico ad una classe, ma sono immutabili.
namespace BlaisePascal.OOPExamples.Presentation.Records;
// Dichiarazione delle proprietà direttamente nel costruttore!
public record IntegerPair(int First, int Second);

Non posso modificarne i valori! Le proprietà sono readonly.
Object.ToString() già implementato di default;
IntegerPair { First = 10, Second = 20 }Object.Equals() già implementato di default;
Funzioni anonime assegnabili ad una variabile. Aumentano la riutilizzabilità del codice.
Struttura:
(<parametri>) => <corpo>
Func<int, int> doubleIt = (int n) => 2 * n;
Func<int, int, int> sum = (int x, int y) => x + y;
Func<int, int, bool> isDivisibleBy = (int n, int d) => n % d == 0;
Predicate<int> isEven = (int n) => isDivisibleBy(n, 2);
// Equivalent:
// Func<int, bool> isEven = (int n) => isDivisibleBy(n, 2);
Action<int> printTests = (int i) =>
{
Console.WriteLine($"Il numero {i}, raddoppiato, vale: {doubleIt(i)}");
Console.WriteLine($"Il numero {i}, sommato a 100, vale: {sum(i, 100)}");
Console.WriteLine($"Il numero {i} è pari? {isEven(i)}");
Console.WriteLine($"Il numero {i} è divisibile per 3? {isDivisibleBy(i, 3)}");
};
// Usage
var numbers = Enumerable.Range(1, 10);
foreach (int i in numbers)
{
printTests(i);
}
Linguaggio di query integrato che permette di applicare trasformazioni a sequenze di dati, rendendo le operazioni di query molto concise.
Voglio stampare, in ordine decrescente, tutti i numeri da 1 a 100 che sono sia pari che > 20.
var numbers = Enumerable.Range(1, 100); // Elenco di numeri da 1 a 100
Opzione 1: Utilizzare la query expression
IEnumerable<int> resultWithExpression =
from number in numbers
where number > 20
where number % 2 == 0
orderby number descending
select number;
Opzione 2: Utilizzare la sintassi a metodi
IEnumerable<int> resultWithMethods = numbers
.Where(n => n > 20)
.Where(n => n % 2 == 0)
.OrderByDescending(n => n);
Confronto tra i due risultati: ottengono la stessa cosa?
Console.WriteLine(
Enumerable.SequenceEqual(resultWithMethods, resultWithExpression)
);
(Output atteso: True)