C#C
C#12mo ago
Faker

Properties vs Fields in C#

Hello guys, can someone explain what is the difference between Properties and Fields in C# please. At first I thought that properties and fields were the same thing because they are accessed the same way, like writing person.name something like that. But this isn't the case. How do properties work? I noticed they work as method but they don't have any parentheses. They should be named the same way as the fields?
c#
public class Person
{
    private int age;  // Private field

    // Property: Combines getter and setter
    public int Age
    {
        get { return age; }              // Getter
        set
        {
            if (value >= 0)              // Validation
                age = value;             // Setter
        }
    }
}
Was this page helpful?