Skip to content

Commit 8a20dff

Browse files
ArgumentOutOfRangeException code example modernization (#7346)
1 parent 85814d8 commit 8a20dff

File tree

2 files changed

+29
-23
lines changed

2 files changed

+29
-23
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>netcoreapp3.1</TargetFramework>
6+
</PropertyGroup>
7+
8+
</Project>
Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,41 @@
11
// <Snippet1>
22
using System;
3+
using static System.Console;
34

4-
class Program
5+
public class Program
56
{
6-
static void Main(string[] args)
7+
public static void Main(string[] args)
78
{
89
try
910
{
10-
Guest guest1 = new Guest("Ben", "Miller", 17);
11-
Console.WriteLine(guest1.GuestInfo());
11+
var guest1 = new Guest("Ben", "Miller", 17);
12+
WriteLine(guest1.GuestInfo);
1213
}
13-
catch (ArgumentOutOfRangeException outOfRange)
14+
catch (ArgumentOutOfRangeException argumentOutOfRangeException)
1415
{
15-
16-
Console.WriteLine("Error: {0}", outOfRange.Message);
16+
WriteLine($"Error: {argumentOutOfRangeException.Message}");
1717
}
1818
}
1919
}
2020

2121
class Guest
2222
{
23-
private string FirstName;
24-
private string LastName;
25-
private int Age;
23+
private const int minimumRequiredAge = 21;
2624

27-
public Guest(string fName, string lName, int age)
28-
{
29-
FirstName = fName;
30-
LastName = lName;
31-
if (age < 21)
32-
throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older.");
33-
else
34-
Age = age;
35-
}
25+
private string firstName;
26+
private string lastName;
27+
private int age;
3628

37-
public string GuestInfo()
29+
public Guest(string firstName, string lastName, int age)
3830
{
39-
string gInfo = FirstName + " " + LastName + ", " + Age.ToString();
40-
return(gInfo);
31+
if (age < minimumRequiredAge)
32+
throw new ArgumentOutOfRangeException(nameof(age), $"All guests must be {minimumRequiredAge}-years-old or older.");
33+
34+
this.firstName = firstName;
35+
this.lastName = lastName;
36+
this.age = age;
4137
}
38+
39+
public string GuestInfo => $"{firstName} {lastName}, {age}";
4240
}
43-
// </Snippet1>
41+
// </Snippet1>

0 commit comments

Comments
 (0)