Introduction to Classes
Introduction to Classes
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:
string typeOfHouse;
int yearBuilt;
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, 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 characteristics to describe an object.
Practical Learning: Introducing Classes
Introduction to Creating a Class
There are various ways you can create a class for an ASP.NET Core Web application. We will see different techniques in future lessons. To start, you can create a class in a text document. To do this, from the Project main menu or the Solution Explorer in the Pages node, choose the New Item option. In the Add New Item dialog box, choose Code File. Give a name to the file, and click Add or press Enter. You can also create a class in the source code of a webpage. To do this, create or use an @functions{} section and include the code of a class in it. To create a simple class, start with a keyword named 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:
@functions{ 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 Code File document or in an @functions{} section. Here is an example in a Code File document:
class House {} class Person {} class MortgageInformation {}
Classes and Files
For your project, you can create each class in its own file or in its own @functions{} section, or you can create various classes in different files or in different @functions{} sections. A class can be created in a file. A file can contain as many classes as necessary. One way you can organize the classes of your application is to put them in different files. A file can contain one or more classes. A file that contains (a) class(es) is a regular text-based file that has the extension .cs.
In the class, you can add the desired members such as regular variables. Here is an example:
@functions{ class Number { } }
Practical Learning: Creating a Class
class Driver { }
/* Piecework is the type of work that is paid on the number * of items produced, the distance driven, etc. * In this exercise, a business uses trucks driven by some * employees or contractors to deliver some products. * The drivers are paid based on the distance they travel to * deliver one or many products. */ class Truck { }
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. To declare a variable in the source code of a webpage, do it in an @{} section. Here are examples:
@functions{ class House { } } @{ // The House class is created in this document House property; // The Boat class is created in a Code File Boat veh; }
The variable of a class can also be declared in the body of another class. Here is an example:
@functions{
class House
{
}
class State
{
// Creating an instance of the House class
House property;
}
}
Value Types and Reference Types
When you declare a variable of a regular type (int, double, etc), 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 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 can be followed by the name of the class followed by parentheses. Here is an example:
@functions{ class House { } } @{ // The House class is created in this document House property = new House(); // The Boat class is created in a Code File Boat veh = new Boat(); }
Practical Learning: Creating an Object
@page
@model PieceWork1.Pages.PieceDeliveryModel
@{
Truck trk = new Truck();
Driver drv = new Driver();
}
Introduction to the Members of a Class
Introduction to the Fields 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
A variable declared in the body of a class is called a field. Each field is declared as a normal variable with a data type followed by a name. 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;
}
}
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. |
Each field can be any of the types we have seen so far. For example, a field of a class can be a Boolean type. To create a Boolean field, declare a variable of type bool in the body of a class. Here is an example:
@{
class Driver
{
bool drivingUnderInfluence;
}
}
Managing Classes
Introduction
Microsoft Visual Studio provides many tools and visual objects used to manage classes of an application. The studio makes it possible to conveniently locate, edit, or rename a class (or one of its members).
The Types Combo Box
The middle-top section of the Code Editor is the Types combo box. It holds a list of the classes in the file that is currently displaying. You can display the list if you click the arrow of the combo box:
The top-right section of the Code Editor displays a combo box named Members. The Members combo box holds a list of the members of the class selected in the Types combo box. Therefore, before accessing the members of a particular class, you must first select that class in the Types combo box. Then, when you click the arrow of the Members combo box, the members of only that class display:
If you select an item from the Members combo box, the Code Editor jumps to that members and positions the cursor to the left of the member.
Accessing a Class
As mentioned already, you can create as many classes as you want for your project. You can create each class in its own file or you can create many classes in the same file. After creating them, to access a class:
Renaming a Class
If you don't like the name a class is using, you can change it. The primary technique consists of locating it in the Code Editor and edit its name. If you use that approach, you will also have to find every section where the name of the class is used. This can be cumbersome and lead to mistakes. If you are working in Microsoft Visual Studio Express, it provides a better solution and would take care of everything behind the scenes.
To rename a class in Microsoft Visual Studio, rn the Code Editor, right-click the name of the class and click Rename...:
This would display a dialog box you can use to indicate what you are planning to do:
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 function 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 fields (member variables):
Source File: ResourcesPart.cs |
partial class Person
{
public string FirstName;
public string LastName;
} |
After creating the class in one file, you can use it like any of the classes as we have done so far. 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; public string Gender; } } |
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 knowledge 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:
Access Modifiers of Class Members
The Private Members of a Class
When it comes to visibility, 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 a keyword named private. Here are examples:
@functions{ class House { string Location; // A private field private string floorPlan; // A private field private int Basement; } }
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 parts of an object that other objects 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 a keyword named public. Here are examples:
@functions{ class House { // A public field public string BuildingPermit; // A public field public double MarketValue; } }
The public and private keywords are referred to as access levels.
By default, if you create a member (field, etc) in a class but don't specify its access level, the member is considered private and cannot be accessed from outside the class, 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: Adding Public Members to a Class
class Driver
{
public string first_name;
public string last_name;
}
/* Piecework is the type of work that is paid on the number
* of items produced, the distance driven, etc.
* In this exercise, a business uses trucks driven by some
* employees or contractors to deliver some products.
* The drivers are paid based on the distance they travel to
* deliver one or many products. */
class Truck
{
public string make;
public string model;
}
Sometimes you want your code to be shared among various languages such as C++/CLI, Visual Basic, F#, etc. In other words, code from these other languages should be able to "read" or access code written in a C# application. To make this possible, a C# class can be created as a public object.
If you want your class to be accessible to code written in other languages, precede the class keyword with the public keyword when creating it. Here is an example:
@functions{ public class Number { int minimum; string sign; } }
Practical Learning: Sharing a Class
/* Piecework is the type of work that is paid on the number
* of items produced, the distance driven, etc.
* In this exercise, a business uses trucks driven by some
* employees or contractors to deliver some products.
* The drivers are paid based on the distance they travel to
* deliver one or many products. */
public class Truck
{
public string make;
public string model;
}
public class Driver
{
public string first_name;
public string last_name;
}
The Internal Members of a Class
Normally, when you create a class, you may want to access its members in various of the project. That is, you may want other classes of the same project to access one or more members of the class, but you may not want other projects to access such a member. If you want to create a member of a class so that only objects of the same project can access that member, you can mark it with the internal keyword.
Initializing an Object
After creating a member of a class, to access it from another class, first declare a variable of 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:
@functions{ class House { public string PropertyType; public int Bedrooms; public double MarketValue; } } @{ 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:
@page @model Valuable.Pages.FoundationsModel @{ House prop = new House(); prop.PropertyType = "Condominium"; prop.Bedrooms = 2; prop.MarketValue = 165820; } @functions{ public class House { public string PropertyType; public int Bedrooms; public double MarketValue; } } <pre>=//= Altair Realtors =//= Properties Inventory Property Type: @prop.PropertyType Bedrooms: @prop.Bedrooms Parmet Value: @prop.MarketValue</pre>
This would produce:
=//= Altair Realtors =//= Properties Inventory Property Type: Condominium Bedrooms: 2 Parmet Value: 165820
Practical Learning: Using Classes
@page @model PieceWork1.Pages.PieceDeliveryModel @{ int miles; double pieceworkRate; Truck trk = new Truck(); Driver drv = new Driver(); drv.first_name = "Lilianne"; drv.last_name = "Gleason"; trk.make = "Ford"; trk.model = "E-350 Rockport Cutaway"; miles = 748; pieceworkRate = .47; string strPay = $"{miles * pieceworkRate}"; } <h3 style="text-align: center"> - Piece Work Delivery -</h3> <hr /> <table width="350" align="center"> <tr> <td width="125">Driver:</td> <td>@drv.first_name @drv.last_name</td> </tr> <tr> <td>Truck Details:</td> <td>@trk.make @trk.model</td> </tr> </table> <hr /> <table align="center" width="350"> <tr> <td width="125">Miles Driven:</td> <td>@miles</td> </tr> <tr> <td>Piecework Rate:</td> <td>@pieceworkRate</td> </tr> <tr> <td>Gross Salary:</td> <td>@strPay</td> </tr> </table>
- Piece Work Delivery - Driver: Lilianne Gleason Truck Details: Ford E-350 Rockport Cutaway Miles Driven: 748 Piecework Rate: 0.47 Gross Salary: 351.56
Generating a Class
To create a class, you can also use skeleton code to start a class:
A class with the default name MyClass would be added. You can accept that name or change it.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2023, C# Key | Wednesday 15 December 2021 | Next |
|