Introduction to Class Classes I
Introduction to Class Classes I
Fundamentals of Classes
Introduction
Imagine you want to describe an object, such as a house. You can declare various variables that each holds one particular value such as the number of bedrooms, the number of doors, the market value of the house, etc. Here is an example:
class Program
{
static void Main()
{
string typeOfHouse;
int numberOfBedrooms;
double price;
}
}
|
When/if you want to describe such a house, you would have to access each variable, one at a time. As opposed to a simple variable, in C#, you can use one or more variables to create one object that includes all the characteristics you want.
A class is a technique of using one or a group of variables to describe an object.
Practical Learning: Introducing Classes
Introduction to Creating a Class
There are various ways you can create a class. We will see different techniques in future lessons. For now, the basic way to start a class is from simple text where you would start with a keyword named class.
Practical Learning: Creating a Class
The Name of a Class
The class keyword is followed by a name. The name of a class primarily follows the rules of names of varibles:
The Body of a Class
To present its description, a class has members. The list of the members of a class is specified after the name of the class. The members are included between an opening curly bracket { and a closing curly bracket }. The section between the curly brackets is referred to as the body of the class. It would appear as follows:
class House { /* . . . */ }
In the same way, you can create as many classes as you want in your project. You can create many classes in the same document. Here is an example:
class House {} class Person {} class MortgageInformation
For your project, you can create each class in its own file or you can create various classes in different files.
To present its description, a class has members. The list of the members of a class is specified after the name of the class. The members are included between an opening curly bracket { and a closing curly bracket }. The section between the curly brackets is referred to as the body of the class. It would appear as follows:
class House { /* . . . */ }
As mentioned above, the members of a class are included inside its curly brackets. Here is an example:
class House { string typeOfHouse; int numberOfBedrooms; double price; }
Although this code is legal, to make it easier to read, you can include each curcly bracket on its own line and each member on its own line, like this:
class House { string typeOfHouse; int numberOfBedrooms; double price; }
To make your code easy to read, it is a good idea to indent the members of a class, like this:
class House { string typeOfHouse; int numberOfBedrooms; double price; }
Again, to make your code better to read, you can put both curly brackets on the same indentation level, like this:
class House { string typeOfHouse; int numberOfBedrooms; double price; }
As mentioned earlier, the variables that are the same type can be declared together using their common type. This can also be done for the members of a class. Here are examples:
class State { string capital; string abbrev, name, dateOfAdmissionToUnion; int orderOfAdmissionToUnion; double areaInSquareMiles, areaInKilometers; }
Practical Learning: Creating a Class
class StoreItem { }
Introduction to the Class View
Microsoft Visual Studio provides many tools to help you create and manage the classes of your project. One of those tools is named the Class View. The Class View is not automatically available when you start a project. To display the Class View:
By default, the Class View displays in the same area as the Solution Explorer. The Class View displays the name of the current project:
If you are working on a solution that involves many projects, the Class View would display each project on its node:
To view the members of a class, expand the node of a project and click the name of the class.
Introduction to Using a Class
Creating an Object
Like any normal variable, to use a class in your program, you must first declare a variable for it. Declaring a variable of a class is also referred to as creating an object or creating an instance of a class.
As done with the variables we have used so far, to declare a variable for a class, use the name of the class followed by a name for the variable. Here is an example:
class House
{
}
class Program
{
static void Main()
{
House property;
}
}
The variable of a class can also be declared in the body of another classe. Here is an example:
class House { } class State { } class Program { State ca; static void Main() { House property; } }
You can also declare variables of different classes in the body of, or outside a class. In C#, the order of appearance of the classes or their variables is not implortant. Here are examples:
class Region { double area; State sc; House nation; State wa; } class House { } class Program { State ca; House condo; State nc; static void Main() { int choice; House property; string selection; House candy; } } class State { House family; }
If various variables are using the same type, you can declare them using their common class name. Separate the names of variables with commas. Here are examples:
class Region { double area; State sc, wa; } class House { } class State { House family, combination, block; } class Program { State ca; Region pacific; House condo static void Main() { House property, candy; } }
Value Types and Reference Types
When you declare a variable of a regular type (string or number), such a value is referred to as a value type. In fact, when you access the value of the variable, you get the actual value itself. The value of such a variable is stored in a memory area referred to as the stack.
After declaring a variable for a class, whenever you need its object, you must use the the address of the memory where the object is stored. This means that you are accessing the object using its reference. For this reason, an object created from a class is stored in a type of memory called the heap.
When declaring a variable for a class, to indicate that its value must be stored in the heap, you must initialize it using an operator called new. This operator is followed by the name of the class followed by empty parentheses. Here is an example:
class House
{
}
class Program
{
static void Main()
{
House property;
property = new House();
}
}
Introduction to the Fields of a Class
Introduction to the Members of a Class
Consider a class named House:
class House { }
As mentioned previously, the section between the curly brackets, { and }, of a class is referred to as its body. In the body of a class, you can create a list of the types that describe an object. These types are referred to as members of the class. At a minimum, these members are created like variables, and therefore are considered member variables.
A Field in a Class
In C#, a variable declared in the body of a class is called a field. Each field is declared as a normal variable with a name and a data type. The name of a variable follows the same rules we reviewed for names of variables. Here is an example of a class with a few fields:
class House
{
int brightness;
string security;
}
Each field can be any type you want.
New Convention:From now on, in our lessons, to refer to a field that belongs to a class, we may write class-name.field-name This means that we are referring to the field field-name that is a member of the class class-name. |
Managing the Fields of a Class
Introduction
To assist you with managing the fields of a class, the Code Editor is equipped with the Types and the Members combo boxes.
The middle combo box displays the class that is currently selected. The right combo box displays the members, such as fields of the class:
Accessing a Field
There are many ways you can access a field:
Renaming a Field
If you decide to use a different name for a field, you can change it. You can first locate the field in the file and use your know of text editing. As an alternative, after opening the file that contains the class, on the main menu, click Edit -> Find & Replace -> Quick Find, type the name of the field, and click Find Next or Replace. This approach is useful if you want to visit every part where the field is used. If you know for sure that you want to rename a field and everywhere it has been used, Microsoft Visual Studio can assist you.
To rename a field in Microsoft Visual Studio:
Introduction to the Properties of a Class
A Property of a Class
As we have seen so far, a class doesn't actually describe an object. It only provides the types of characteristics of an object. When you declare a variable of a class, then you can access those types to describe an object using formal values. To make it possible for a class to exchange values with the external world, a class must be equipped with special members called properties.
A property is a class member that allows external objects (variables declared from that class) to pass values to the class or for external objects to get values from the class. When you create a class, you also decide what properties you need. This means that you must create properties for your class and you decide what properties are necessary. The basic formula to create a property is:
options data-type property-name { get; set; }
Throughout our lessons, we will find out what the starting options are (for now, let's ignore them). By the way, unlike some languages (like Visual Basic), C# doesn't use property as a keyword.
When creating a property, you must specify a valid data type. It can be one of those we have used so far (string, int, or double). The data type is followed by a valid name for the property. The name follows the rules of names of classes. For our formula, the creation of a property ends with { get; set; } (you can omit that expression, but then the member becomes a field and not a property). Here is an example of a property created in a class:
class House
{
double MarketValue { get; set; }
}
New Convention:From now on, in our lessons, to refer to a property that belongs to a class, we may write class-name.property-name This means that we are referring to the property property-name that is a member of the class class-name. |
Practical Learning: Adding Properties to a Class
class StoreItem
{
int ItemNumber { get; set; }
string ItemName { get; set; }
string Size { get; set; }
double UnitPrice { get; set; }
}
Access Modifiers of Class Members
The Private Members of a Class
The parts of an object fall into two main categories: those you can touch and those you don't have access to. The parts you cannot access or cannot see are referred to as private. When creating a class, to specify that a member must be hidden to outside objects, precede its declaration with the private keyword. Here are examples:
class House { string Location; // A private field private string floorPlan; // A private property private int Basement { get; set; } }
When a member is marked private, other members of the same class can access it. Objects outside the class and members of other classes cannot access a private member.
The Public Members of a Class
The parts of an object that you have access to are referred to as public. To indicate that a member of a class must be accessible outside the class, precede its declaration with the public keyword. Here are examples:
class House { // A public field public string BuildingPermit; // A public property public double MarketValue { get; set; } }
The public and private keywords are referred to as access levels.
By default, if you create a member (field, property, etc) in a class but don't specify its access level, the member is considered private and cannot be accessed from outside, that is by a non-member, of that class. Therefore, to make a member accessible by other classes, you must mark it as public.
You can use a mix of public and private members in a class and there is no rule on which access level should be listed first or last. To reduce confusion as to what member is public or private, you should always specify the access level of each member.
Practical Learning: Specifying the Access Modifiers of Fields
class StoreItem { public int ItemNumber { get; set; } public string ItemName { get; set; } public string Size { get; set; } public double UnitPrice { get; set; } }
Initializing an Object
The Period Operator
After creating a member of a class, to access it from another class, first declare a variable from its class as we know already. To actually access the member, use the period operator ".".
After declaring an instance of a class, you can access each of its members and assign it the desired value. Here is an example:
class House { public string PropertyType{ get; set; } public int Bedrooms { get; set; } public double MarketValue { get; set; } } class Program { static void Main() { House prop = new House(); prop.PropertyType = "Condominium"; prop.Bedrooms = 2; prop.MarketValue = 165820; } } |
Once a field has been initialized, you can use the period operator to access it and retrieve its value:
class House { public string PropertyType{ get; set; } public int Bedrooms { get; set; } public double MarketValue { get; set; } } class Program { static void Main() { House prop = new House(); prop.PropertyType = "Condominium"; prop.Bedrooms = 2; prop.MarketValue = 165820; System.Console.WriteLine("=//= Altair Realtors =//="); System.Console.WriteLine("Properties Inventory"); System.Console.Write("Property Type: "); System.Console.WriteLine(prop.PropertyType); System.Console.Write("Bedrooms: "); System.Console.WriteLine(prop.Bedrooms); System.Console.Write("Parmet Value: "); System.Console.WriteLine(prop.MarketValue); } }
This would produce:
=//= Altair Realtors =//= Properties Inventory Property Type: Condominium Bedrooms: 2 Market Value: 165820 Press any key to continue . . .
Practical Learning: Using a Class' Fields
|
Introduction to the Methods of a Class
Overview
A function is an action that an object performs. It resembles a verb in the English language (or any language for that matter). A function can be created as a member of a class. A function that is a member of a class is called a member function or more precisely a method.
Introduction to Creating a Method
The primary formula to create a method is:
options return-type method-name(){}
You can omit or start with one or more options. Throughout our lessons, we will find out what options are available. A method is usually made to produce a value. If you don't plan to get a value from it, then you must start with the void keyword. Like everything else, a method must have a name. The name of a method primarily follows the rules and conventions of named of classes and properties. When it comes to methods, the name usually reflects an action or a verb. The name of a method is followed by parentheses and curly brackets. Here is an example:
class House
{
public string PropertyType { get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
void ProtectFromBadWeather() { }
}
As mentioned for a class, the section between the curly brackets is referred to as the body of the method. This is where you will include code for the method. If the method contains many lines of code, the brackets should be used on different lines. Here is an example:
class House
{
public string PropertyType { get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
void ProtectFromBadWeather()
{
}
}
As mentioned for fields and methods, a method can be made public or private. If the access level is not specified, the method is considered private. If you want the method to be accessed outside the class, mark it as public. To make your code easier to read, you should mark each method with an access level. Here are examples:
class House { public string PropertyType{ get; set; } public int Bedrooms { get; set; } public double MarketValue { get; set; } private void ProtectFromBadWeather() { } public void ShowPropertyCharacteristics() { } }
Calling a Method
After creating a method, accessing it is referred to as calling it. As mentioned for fields and properties, if you create a private method, it can be accessed by only members of the same class. On the other hand, after creating a public method, to access it outside the class, declare a variable of the class and use the period operator to access the method. Here is an example:
class House
{
public string PropertyType{ get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
private void ProtectFromBadWeather()
{
}
public void ShowPropertyCharacteristics()
{
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("Properties Inventory");
System.Console.Write("Property Type: ");
System.Console.WriteLine(PropertyType);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(Bedrooms);
System.Console.Write("Parmet Value: ");
System.Console.WriteLine(MarketValue);
}
}
class Program
{
static void Main()
{
House prop = new House();
prop.PropertyType = "Condominium";
prop.Bedrooms = 2;
prop.MarketValue = 165820;
prop.ShowPropertyCharacteristics();
}
}
New Convention:From now on, in our lessons, to refer to a method that belongs to a class, we may write class-name.method-name() This means that we are referring to the method method-name that is a member of the class class-name. |
Introduction to Constructors
Introduction to the Constructor of a Class
When you create an object (a variable declared from a class), you are in fact describing an object. In some cases, you may want that object to hold some default characteristics so that you don't have to work from scratch. A constructor is a special method that specifies the primary information of an object.
Creating a Constructor
A constructor is created as a method of a class. A constructor has two primary characteristics as follows:
Here is an example of a constructor in a class named House:
class House
{
public House()
{
}
}
Other than that, a constructor uses many of the characteristics we will learn about methods.
Of course, a class can have various types of members (such as fields, properties, methods, etc) and constructors (as we will see in later lessons, a class can have many constructors). Here is an example of a class that has properties and a constructor:
class House
{
public House()
{
}
public string PropertyType{ get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
}
In the body of a class, the order of appearance of the members is not important. This means that you can first create a constructor followed by other members, first the members and a constructor last, or a constructor between members. Here is an example:
class House
{
public int PropertyNumber { get; set; }
public double Bathrooms { get; set; }
public House()
{
}
public string PropertyType{ get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
}
Calling a Constructor
From our introductions, we saw that, when declaring a variable from a class, after the new operator, you must write the name of the class followed by parentheses. Here is an example we saw:
class House
{
public string PropertyType { get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
public House()
{
/* PropertyType = "Single-Family";
Bedrooms = 5;
MarketValue = 495_680; */
}
}
class Program
{
static void Main()
{
House prop = new House();
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("=============================");
System.Console.WriteLine("Properties Inventory");
System.Console.WriteLine("-----------------------------");
System.Console.Write("Property Type: ");
System.Console.WriteLine(prop.PropertyType);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(prop.Bedrooms);
System.Console.Write("Parmet Value: ");
System.Console.WriteLine(prop.MarketValue);
System.Console.WriteLine("=============================");
}
};
This would produce:
=//= Altair Realtors =//= ============================= Properties Inventory ----------------------------- Property Type: Bedrooms: 0 Parmet Value: 0 ============================= Press any key to continue . . .
In reality, when you declare a variable like that, you are actually calling the constructor of the class. As a result, the primary role of a constructor is to provide the primary or default characteristics of an object created from a class. Therefore, in the body of a constructor, you can access each property and assign the desired value to it. Here is an example:
class House
{
public string PropertyType { get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
public House()
{
PropertyType = "Single-Family";
Bedrooms = 5;
MarketValue = 495_680;
}
}
class Program
{
static void Main()
{
House prop = new House();
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("=============================");
System.Console.WriteLine("Properties Inventory");
System.Console.WriteLine("-----------------------------");
System.Console.Write("Property Type: ");
System.Console.WriteLine(prop.PropertyType);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(prop.Bedrooms);
System.Console.Write("Parmet Value: ");
System.Console.WriteLine(prop.MarketValue);
System.Console.WriteLine("=============================");
}
}
This would produce:
=//= Altair Realtors =//= ============================= Properties Inventory ----------------------------- Property Type: Single-Family Bedrooms: 5 Parmet Value: 495680 ============================= Press any key to continue . . .
Introduction to Parameters and Arguments
Introduction to the Parameters of a Method
To perform its action(s), a function or method may need some values. If you are creating a method that will need values, you must indicate it. To do this, in the parantheses of the method, enter the data type and a name for each value. Here is an example of a method that will need one value as a string:
class House
{
private void ProtectFromBadWeather(string typeOfRoof)
{
}
}
The combination of data type and name that you provide to the method is called a parameter. In the body of the method, you can use the parameter or ignore it completely. When using the parameter, you can involve it in any operation that is appropriate for its type. For example, if it is a number (integer or floating-point number), you can involve it in any algebraic operation. If it is a string or any other type, use it anyway you want. Here is an example:
class House { private void ProtectFromBadWeather(string typeOfRoof) { System.Console.Write("Roof Type: "); System.Console.WriteLine(typeOfRoof); } }
In the body of the method, you can also ignore the parameter. This means that, in the body of the method, you can decide not to use a parameter.
Calling a Method that Uses a Parameter
When calling a method that uses a parameter, you must provide a value for the parameter. The value provided in the parentheses of the method is called an argument. The action of providing a value in the parentheses of the method is referred to as passing an argument to the method.
There are various ways you can pass an argument to a method. If you have the value you want to use, provide it in the parentheses of the method. Here is an example:
class House
{
public string PropertyType{ get; set; }
public int Bedrooms { get; set; }
public double MarketValue { get; set; }
private void ProtectFromBadWeather(string typeOfRoof)
{
System.Console.Write("Roof Type: ");
System.Console.WriteLine(typeOfRoof);
}
public void ShowPropertyCharacteristics()
{
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("Properties Inventory");
System.Console.Write("Property Type: ");
System.Console.WriteLine(PropertyType);
ProtectFromBadWeather("Asphalt Shingles");
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(Bedrooms);
System.Console.Write("Market Value: ");
System.Console.WriteLine(MarketValue);
}
}
If the value is stored in a variable, you can pass the name of the variable to the method. Here is an example:
class House { public string PropertyType{ get; set; } public int Bedrooms { get; set; } public double MarketValue { get; set; } private void ProtectFromBadWeather(string typeOfRoof) { System.Console.Write("Roof Type: "); System.Console.WriteLine(typeOfRoof); } public void ShowPropertyCharacteristics() { string roofMaterial = "Asphalt Shingles"; System.Console.WriteLine("=//= Altair Realtors =//="); System.Console.WriteLine("Properties Inventory"); System.Console.Write("Property Type: "); System.Console.WriteLine(PropertyType); ProtectFromBadWeather(roofMaterial); System.Console.Write("Bedrooms: "); System.Console.WriteLine(Bedrooms); System.Console.Write("Market Value: "); System.Console.WriteLine(MarketValue); } }
A Method With Many Parameters
A method can use as many parameters as you judge them necessary. When creating such a method, in its parentheses, provide each parameter by its data type and a name. The parameters are separated by commas. The parameters can be of the same type. Here is an example:
class TimeSheet
{
public void ShowTimeWorked(string startTime, string endTime)
{
}
}
The parameters can also be of different types. Here is an example of a method that uses 3 parameters:
class TimeSheet
{
public void ShowTimeWorked(string startTime, int timeWorked, string endTime)
{
}
}
As mentioned earlier, you don't have to use a parameter in the body of the method if you don't have use for it. Otherwise, in the body of the method, you can use the parameters any appropriate way you want.
When calling a method that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses.
Introduction to the Characteristics of a Class
Introduction to Default Constructors
Like other methods, constructors have various characteristics. For example, in later lessons, we will learn that a constructor can use parameters. If you create a constructor that has empty parentheses (a constructor without parameters), that constructor is called the default constructor.
In C#, you can create a class (the same class) in different files. This means that you can start a class in one file and continue it in another file or in other files. This is referred to as partial implementation.
As we have seen so far, in C#, you cannot simply and only declare a method in a file for a forward (later) implementation. In C#, to create a class in various files, start the class in one file but precede the class keyword with partial. Here is an example of a file named ResourcesPart.cs that contains some (2) private fields and some (2) properties:
Source File: ResourcesPart.cs |
partial class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
|
After creating the class in one file, you can use it like any of the classes as we have done so far. Here is an example:
Source File: Exercise.cs |
class Exercise
{
static void Main()
{
Person pers = new Person();
pers.FirstName = "John";
pers.LastName = "Foster";
System.Console.WriteLine("Personal Identification");
System.Console.WriteLine("-----------------------");
System.Console.Write("First Name: ");
System.Console.WriteLine(pers.FirstName);
System.Console.Write("Last Name: ");
System.Console.WriteLine(pers.LastName);
System.Console.WriteLine("=======================");
}
} |
This would produce:
Personal Identification ----------------------- First Name: John Last Name: Foster ======================= Press any key to continue . . .
If you had created a partial class, or you got a partial class from somebody (not as part of a DLL nor from another type of library), and you find out that the class is not complete, you can then complement it. There are rules you must follow:
One of the advantages of partial implementation is that you don't have to get back to the first or previous file to modify it in order to complement the class. You can simply start another file and continue the class in it. Here is an example:
Source File: Human.cs |
partial class Person { public string DateOfBirth { get; set; } public string Gender { get; set; } } } |
Source File: Exercise.cs |
class Exercise { static void Main() { Person pers = new Person(); pers.FirstName = "John"; pers.LastName = "Foster"; pers.Gender = "Male"; pers.DateOfBirth = "10/04/2016"; System.Console.WriteLine("Personal Identification"); System.Console.WriteLine("-----------------------"); System.Console.Write("First Name: "); System.Console.WriteLine(pers.FirstName); System.Console.Write("Last Name: "); System.Console.WriteLine(pers.LastName); System.Console.Write("Date of Birth: "); System.Console.WriteLine(pers.Gender); System.Console.Write("Gender: "); System.Console.WriteLine(pers.DateOfBirth); System.Console.WriteLine("======================="); } } |
This would produce:
Personal Identification ----------------------- First Name: John Last Name: Foster Date of Birth: Male Gender: 10/04/2016 ======================= Press any key to continue . . .
The Scope and Lifetime of a Variable
Introduction
The scope of a variable is the extent to which it is available to other members of a class. To manage this, a variable is said to have local or global scope.
Local Variables
A variable is said to be local if it is declared in the body of a method. Here is an example:
class MemberRegistration
{
private void Create()
{
string middleName;
}
}
When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.
A Global Variable
A variable is said to be global if it is declared inside the body of a class and outside the curly brackets of any method. Here is an example:
Here is an example:
class MemberRegistration
{
string strDateOfBirth;
private void Initialize()
{
}
private void Present()
{
}
}
A variable that has been declared globally can be accessed by any code of the same class.
The Scope and Lifetime of an Object
You can declare a variable of a class in the body of a class and initialize it there. Here is an example:
class Student
{
}
class StudentRegistration
{
Student pupil = new Student();
private void Show()
{
}
}
Once this has been done, the object is ready to be used by any method of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a method of the class. Here is an example:
class Student { } class StudentRegistration { Student pupil; private void Create() { pupil = new Student(); } private void Show() { } }
If you decide to use this technique, before the object can be actually used, you must call the method that initializes the variable, otherwize you may receive an error.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2021, C# Key | Next |
|