Thursday, July 15, 2010

Properties (Get/Set Alternate) - C#

If any of you have experience with Get/Set methods for variables, you know how tedious it can be to create multiple simple method for each variable, especially in a class where with many variables.

Starting with C# 3.0, there is an easier way to access and modify class variables, called properties.

Let's say you create a class called student, which has two variables, ID and Name.
public class Student
{
   public int ID{get; set;}
   public string Name {get; set;}
}
Instead of having to write a method like getID and setID, the variables can now be accessed by simply doing ClassName.ID.

Example:
Student calvin = new Student();

calvin.ID = 44;
calvin.Name = "Calvin";
Console.WriteLine("Student {0} has an ID # {1}", calvin.Name, calvin.ID);
Output = "Student Calvin has an ID # 44"

0 comments:

Post a Comment