C# Classes and Objects
ExampleC#
using System;
class Person
{
public string Name { get; set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void Birthday()
{
Age++;
}
public override string ToString()
{
return Name + " is " + Age;
}
}
class Program
{
static void Main()
{
Person p = new Person("Ada", 36);
p.Birthday();
Console.WriteLine(p);
p.Name = "Grace";
Console.WriteLine(p.Name);
}
}Output
Ada is 37 Grace
{ get; set; } declares a property: a field with built-in access. private set means only the class itself can change Age.
Quick check
What does { get; private set; } mean?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.