Introduction to Objects and Classes in C#, Part 2 - Comments
(Page 2 of 4 )
When you write applications in C# try to use comments to describe exactly how your application performs and why; try to make your application easy to understand and easy to maintain. Think about it this way: if you were to come back to your application five years after you wrote it, would you know what every line of code meant and did? What if someone was developing an application and they were trying to read through your code? Without documentation, this is difficult even for the most experienced programmers.
I think that you want to know more about classes so let's write a class and then discuss new concepts.
The Person Class
Here's a simple class called Person
class Person
{
// These are 3 private instance variables
// for now just consider them instance members of
// that class
private string firstName;
private string lastName;
private int age;
// This called the default constructor
public Person()
{
firstName = "Unknown";
lastName = "Unknown";
age = 0;
}
// This also a Constructor and we will understand
// the use of it and why we create constructors
public Person(string fName, string lName, int pAge)
{
firstName = fName;
lastName = lName;
age = pAge;
}
// This is a method just writes a string to the console.
// this string consists of the 3 variables and
// displaying the information about the person.
public void PersonInfo()
{
Console.WriteLine("First Name = {0}, Last Name = {1} and his age = {2}",
firstName, lastName, age);
}
}
Let's break this down:
You're probably curious about private string firstName, private string lastName, and private int age. These are called instance variables, and as you know from the first part of that article, when you create objects from a given class (for example, the person class) you create an instance of that class. That's why we call the variables declared the body of the class (but not inside any method of that class) an instance variable. When you create an objects of that class C# compiler will allocate separate memory locations for the instance variables of each object. Thus, the object named Michael (of type Person) will contain its own values for these instance members, as will the object Prakhar (of type Person). You can say that the consumer application (the application that will use your class) will provide the values of these instance variables for each object created of that type.
NOTE About the keywords private and public in the class, they called access modifier keywords. When developing C# class you will use the access modifier keywords to specify the scope of the member. Each instance variable, method, or any other type you create inside a class called a member. C# gives you the power to specify the scope of the member using these access modifiers.
Next: What's a Scope? >>
More C# Articles
More By Michael Youssef