diff --git a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty.csproj b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty.csproj index 2150e3797b..ed9781c223 100644 --- a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty.csproj +++ b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net10.0 enable enable diff --git a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/RectangleWithFieldKeyword.cs b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/RectangleWithFieldKeyword.cs new file mode 100644 index 0000000000..87e5581315 --- /dev/null +++ b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/DifferenceBetweenFieldsAndProperty/RectangleWithFieldKeyword.cs @@ -0,0 +1,14 @@ +namespace DifferenceBetweenFieldsAndProperty; + +// The same validation as Rectangle.Width, written with the C# 14 `field` keyword +// instead of a hand-declared private backing field. +public class RectangleWithFieldKeyword +{ + public double Width + { + get; + set => field = value >= 0 + ? value + : throw new ArgumentException("A Rectangle can't have negative width", nameof(value)); + } +} diff --git a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.cs b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.cs index 9e2c39891f..054b34b8af 100644 --- a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.cs +++ b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.cs @@ -20,4 +20,20 @@ public void GivenRectangle_WhenScaling_ThenReturnsScaledDimensions() Assert.Equal(105, scaledRectangle.Height); } + + [Fact] + public void GivenRectangleWithFieldKeyword_WhenAssigningNegativeWidth_ThenThrowsException() + { + var rectangle = new RectangleWithFieldKeyword(); + + Assert.Throws(() => rectangle.Width = -2); + } + + [Fact] + public void GivenRectangleWithFieldKeyword_WhenAssigningValidWidth_ThenStoresValue() + { + var rectangle = new RectangleWithFieldKeyword { Width = 14 }; + + Assert.Equal(14, rectangle.Width); + } } \ No newline at end of file diff --git a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.csproj b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.csproj index 3ae64a9baf..2447f831b6 100644 --- a/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.csproj +++ b/csharp-intermediate-topics/DifferenceBetweenFieldsAndProperty/Tests/Tests.csproj @@ -1,7 +1,7 @@ - net8.0 + net10.0 enable enable