Skip to content

Commit 9b27d62

Browse files
Refactor Person class properties and methods
Refactor properties to use expression-bodied members and remove 'this' references for clarity.
1 parent 103b0b7 commit 9b27d62

File tree

1 file changed

+8
-27
lines changed

1 file changed

+8
-27
lines changed

samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-methods.cs

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,46 +9,27 @@ public class Person
99

1010
public Person(string firstName, string lastName)
1111
{
12-
// Add 'this' to each property for better clarification
13-
this.fname = firstName;
14-
this.lname = lastName;
12+
fname = firstName;
13+
lname = lastName;
1514
}
1615

17-
// Add public properties
16+
public string FirstName { get; private set }
1817

19-
public string FirstName
20-
{
21-
get => this.fname;
22-
23-
private set
24-
{
25-
this.fname = value;
26-
}
27-
}
28-
29-
public string LastName
30-
{
31-
get => this.lname;
32-
33-
private set
34-
{
35-
this.lname = value;
36-
}
37-
}
18+
public string LastName { get; private set }
3819

3920
/// <summary>
4021
/// Add some changes in methods
4122
/// </summary>
4223
/// <returns></returns>
4324

44-
public override string ToString() => $"{this.FirstName} {this.LastName}".Trim();
25+
public override string ToString() => $"{FirstName} {LastName}".Trim();
4526
public void DisplayName() => Console.WriteLine(ToString());
4627

4728
// Expression-bodied methods with parameters
48-
public string GetFullName(string title) => $"{title} {this.FirstName} {this.LastName}";
29+
public string GetFullName(string title) => $"{title} {FirstName} {LastName}";
4930
public int CalculateAge(int birthYear) => DateTime.Now.Year - birthYear;
5031
public bool IsOlderThan(int age) => CalculateAge(1990) > age;
51-
public string FormatName(string format) => format.Replace("{first}", this.FirstName).Replace("{last}", this.LastName);
32+
public string FormatName(string format) => format.Replace("{first}", FirstName).Replace("{last}", LastName);
5233
}
5334

5435
class Example
@@ -65,4 +46,4 @@ public static void Main()
6546
Console.WriteLine($"Is older than 25: {p.IsOlderThan(25)}");
6647
Console.WriteLine(p.FormatName("Last: {last}, First: {first}"));
6748
}
68-
}
49+
}

0 commit comments

Comments
 (0)