-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
57 lines (50 loc) · 1.92 KB
/
Program.cs
File metadata and controls
57 lines (50 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// C# 14 – field keyword (Field-Backed Properties)
// https://learn.microsoft.com/en-gb/dotnet/csharp/whats-new/csharp-14#the-field-keyword
// https://devblogs.microsoft.com/dotnet/csharp-14-field-keyword/
// Real-world scenario: a customer account in a banking/e-commerce application.
// The email is normalized, the credit limit cannot be negative, and the name field cannot be left empty.
var account = new CustomerAccount("ibrahim")
{
Email = " Ibrahim.Atay@contact ",
CreditLimit = 50_000m
};
Console.WriteLine($"Name : {account.FullName}");
Console.WriteLine($"Email : {account.Email}"); // normalized
Console.WriteLine($"CreditLimit : {account.CreditLimit:C}");
try
{
account.CreditLimit = -100m; // validation kicks in
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
public class CustomerAccount(string fullName)
{
// The primary constructor parameter is used together with the field keyword.
// An empty name is not accepted.
public string FullName
{
get => field;
set => field = string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Name cannot be empty.", nameof(value))
: value.Trim();
} = fullName;
// Normalization: the email is always stored as trimmed + lowercase.
// No need to declare a separate private backing field.
public string Email
{
get => field;
set => field = value?.Trim().ToLowerInvariant() ?? string.Empty;
}
// Validation: the credit limit cannot be negative.
// Since the backing field cannot be accessed from elsewhere in the class,
// the validation is always enforced (encapsulation is preserved).
public decimal CreditLimit
{
get => field;
set => field = value >= 0
? value
: throw new ArgumentOutOfRangeException(nameof(value), "Credit limit cannot be negative.");
}
}