I am new to C#, and writing a piece of code to do some exercises. What surprises me is that I can use undefined member variables in a C# class as if they had been defined. Below is my code. In class Person, I only defined "myName" and "myAge," but I can use the member variables "Name" and "Age" without any issue. The code can be compiled and the executable can be run. Can someone tell me why I can use "Name" and "Age" without defining them? Many thanks,
C# code
====================================== using System;
namespace prj01
{
class Person
{
private string myName = "N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
}
class Program
{
static void Main(string[] args)
{
// property
Console.WriteLine("Simple Properties");
Person person01 = new Person();
Console.WriteLine("Person details - {0}", person01);
person01.Name = "Joe"; // Why can I use "Name"?
person01.Age = 99; // Why is "Age" accessible and usable?
Console.WriteLine("Person details - {0}", person01);
Console.ReadLine();
}
}
}
======================================