C# Tutorial - ClassesA class is an abstract representation for some particular type of object. It can be described as a template or blueprint for an object, as opposed to the actual object itself. Thus, objects are an instance of a class - they come into existence at some specific time, persist for some duration, and then disappear when they are no longer needed. Classes are the abstract descriptions used by the system to create objects when called upon to do so. A class contains attributes (information) and methods (behaviour) that act upon the attributes. So what does a class look like? If we look at our person object, we can use this to create an example class. class Person
{
. . .
}
We declare our class using the keyword class, followed by the name of our class, which in this case is Person. We then use the curly braces ({}) to show the start and end of the class, which also defines the scope of the data used in the class. What this means is that all attributes and methods associated with the class must be between the two curly braces. AttributesThe data located within a class are referred to as variables or attributes. They can be of any data type including other classes. class Person
{
// Attributes
private string _forename;
private string _surname;
}
An attribute is always declared in the following manner: [access-modifier] data-type attribute-name; Where:
Each attribute definition is terminated with a semicolon (;). MethodsMethods are functions that manipulate the data associated with an object or perform some other operation relevant to the object. A method can be thought of as a named sequence of statements. So let us add two methods to our Person class. class Person
{
// Attributes
private string forename;
private string surname;
. . .
// Methods
public void setSurname( string aSurname )
{
surname = aSurname;
}
public string getSurname()
{
return surname;
}
}
A method is always declared in the following manner: [access-modifier] return-type method-name( [parameter-list] )
{
method-body-statements;
}
Where:
|