Introduction to Classes
To use a variable, you can declare it using either var or a known and simple data type. For example, to use an integer, you can declare a variable that…
Fundamentals of Classes#
Introduction#
To use a variable, you can declare it with either var or a known and straightforward data type. For example, to use an integer, you can declare a variable that represents the number of bedrooms of a house. Here is an example:
<%@ Page Language="C#" %>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
int bedrooms = 3;
%>Variables can be initialized using either the 'var' keyword or a specific data type. This flexibility allows developers to choose between implicit and explicit typing based on their needs.
- Start Microsoft Visual Web Developer
- To create a new web site, on the main menu, click File -> New Web Site...
- Make sure the Language is set to Visual C#. Click the second box to the right of Location, delete the suggested name of the web site and replace it with geometry5
- Click OK
- In the Solution Explorer, right-click Default.aspx and click Rename
- Type index.aspx and press Enter
Creating a Class#
A class is a technique of using one or a group of variables to be used as a foundation for a more detailed variable. Before creating a class, create a sub-folder where you would store the class. This means that you must create the sub-folder inside the folder that contains the regular files like index.htm or index.aspx. If you use Visual Web Developer, to create a folder, in the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click Folder. Type the name of the folder and press Enter. To create a new class, you can right-click the name of the folder, position the mouse on Add, and click Folder. Otherwise, when you create a new class, Visual Web Developer would ask you if you want it to create the new folder for you. If (since you will) agree, it would create a sub-folder named App_Code. To create a class, you start with the class keyword followed by a name and its body delimited by curly brackets. Here is an example of a class called House:
class House
{
}When saving the file that contains the class, remember to store it in the sub-folder indicated above. If you are working in the Visual Web Developer or Microsoft Visual Studio, when a project is made of various files, each file is represented by a tab in the top section of the Code Editor. To access a file, you can click its tab. Practical Learning: Creating a Class
- In the Solution Explorer, right-click geometry5 and click Add New Item...
- In the Templates list, click Class
- Replace the suggested name with Cylinder
- Click Add
- Read the message box that comes up and click Yes
Visually Managing Classes#
To assist you with managing the various classes of a project, the Visual Web Developer includes various tools and windows. One of the windows you can use is called the Class View. To display it, on the main menu, you can click View -> Class View. The Class View is made of four sections. The toolbar under the title bar includes many buttons. To identify a button, you can position the mouse on it and a tool tip would appear. To add a new class, besides the main menu, you can right-click the name of the project in the Class View and New Item...
Declaring a Variable of a Class Type#
Like any normal variable, to use a class in your program, you can first declare a variable for it. To declare a variable of a class, you can use the var keyword. Alternatively, you can type its name followed by a name for the variable. For example, to declare a variable of the above House class, you could type the following:
var property . . .Or the following:
House property;The variables we have declared so far are called value variables. This is because such variables of primitive types hold their value. The C# language supports another type of variable. This time, when you declare the variable, its name does not hold the value of the variable; it holds a reference to the address where the actual variable is stored in memory. This reference type is the kind used to declare a variable for a class. To use a variable as reference, you must initialize it using an operator called new. Here is an example:
var Property = new House();If you are using the name of the class instead of var to declare the variable, you can first declare it. Then, on another line, you can allocate memory for it using the new operator. Here is an example:
House Property;
// You can do something here
Property = new House();If you create a class in any of the files that belong to the same project, the class is made available to all other files of the same project. Practical Learning: Using a Class
- In the Code Editor, click the index.aspx tab
- To use the new class, change the code as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title> Geometry: Cylinder </title> </head> <body> <% var Cup = new Cylinder(); %> </body> </html>
- Save the file
Sharing a Class#
Unlike its sisters the C and the C++ languages, C# was developed with the idea of working complementarily with other languages such as C++/CLI, Visual Basic, and J#. 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 public when creating it. Here is an example:
public class House
{
}Garbage Collection#
When you initialize a variable using the new operator, you are in fact reserving some space in the heap memory. The memory is "allocated" for the variable. When that variable is no longer needed, such as when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs. This is referred to as garbage collection. In the past, namely in C/C++, this was a concern for programmers because they usually had to remember to manually delete such a variable (a pointer) and free its memory. The .NET Framework solves the problem of garbage collection by "cleaning" the memory after you. This is done automatically when necessary so that the programmer doesn't need to worry about this issue.
Class' Fields#
Introduction#
Consider a class named House:
public class House
{
}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 parts that make up the class. Each of these parts must be a complete variable with a name and a data type. For example, here are the characteristics that make up a house, declared as the parts of the above class and each declared as a variable:
public class House
{
string PropertyNumber;
char PropertyType;
byte Stories;
uint bedrooms;
decimal Value;
}Unlike its predecessors C and C++, C# was designed from the ground up for the .NET ecosystem. This managed environment provides features like automatic memory management and enhanced security.
Accessing Class Members#
Private Members#
The parts of an object fall into two main categories: those you can touch and those you don't have access to. For example, for a car parked at the mall, you can see or touch its doors and its tires but you don't see its engine or its spare tire, you don't even know if it has one. The parts of an object that you have access to are referred to as public. Those you can't see or touch are referred to as private. A C# class also recognizes that some parts of a class can be made available to other classes and some other parts can be hidden from other classes. A part that must be hidden from other classes is private and it can be declared starting with the private keyword. If you declare a member variable and want to make it available to other classes, you must start its name with the public keyword. The public and private keywords are referred to as access level. By default, if you declare a member variable (or anything else) 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 declare 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. Here are examples:
public class House
{
string PropertyNumber;
public char PropertyType;
byte Stories;
public uint bedrooms;
private decimal Value;
}Just keep in mind that if you omit or forget the access level of a member of a class, the member is automatically made private. To reduce confusion as to what member is public or private, you should always specify the access level of a member variable.
public class House
{
public string PropertyNumber;
public char PropertyType;
public byte Stories;
public uint Bedrooms;
public double Value;
}After creating a member of a class, to access it from another class, first declare a variable from its class as we saw earlier. To actually access the member, use the period operator ".". Practical Learning: Adding Fields to a Class
- In the Code Editor, click the Cylinder.cs tab
- To add new fields to the class, change it as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Cylinder /// </summary> public class Cylinder { public double rad; public double hgt; }
- Click the index.aspx tab
- To prepare to show the values of the cylinder, change the code as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Geometry: Cylinder</title> </head> <body> <% var Cup = new Cylinder(); Response.Write("=-=Cylinder Characteristics=-="); Response.Write("<br>Radius: "); Response.Write(Cup.rad); Response.Write("<br>Height: "); Response.Write(Cup.hgt); %> </body> </html>
- Save the file
Internal Members#
We have seen that the public keyword is used to let objects of the same program and objects of other programs access the public member. The private keyword is used to let only members of a class access the (private) member of the class. If you want to create a member of a class so that only objects of the same program can access that member, you can mark it with the internal keyword. The differences between these keywords can be resumed as follows:
| If a class member is marked as | |||
|---|---|---|---|
| public | private | internal | |
| Members of its class can access this member | Yes | Yes | Yes |
| Members of this program, including outside of the class, can access this member | Yes | No | Yes |
| Objects outside of this program can access this member | Yes | No | No |
Initializing an Object#
Introduction#
After declaring an instance of a class, you can access each of its members and assign it the desired value. Here is an example:
<%@ Page Language="C#" %>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
Property = new House();
Property.PropertyNumber = "283795";
Property.PropertyType = "Single Family";
Property.Bedrooms = 4;
Property.Value = 652880;
%>Once a member variable has been initialized, you can use the period operator to access it and retrieve its value. Practical Learning: Initializing an Object
- To initialize a Cylinder object, change the code as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Geometry: Cylinder</title> </head> <body> <% var Cup = new Cylinder(); Cup.rad = 22.08; Cup.hgt = 28.14; Response.Write("=-=Cylinder Characteristics=-="); Response.Write("<br>Radius: "); Response.Write(Cup.rad); Response.Write("<br>Height: "); Response.Write(Cup.hgt); %> </body> </html>
- Press Ctrl + F5 to see the result
- Close the browser
Using an Anonymous Type#
We saw that, to use a class, you could first declare a variable for it and initialize it. Fortunately, you don't have to use a class to initialize an object. You can declare a variable that resembles an instance of a class and initialize it as you see fit. This is referred to as an anonymous type. To use it, declare the variable using the var keyword and use the new operator to allocate memory for it. Instead of using the name of a class, type an opening and a closing curly brackets after the new operator. In the curly brackets, state a name for each member as if it were the member of the class and initialize each member variable with the desired value. After the closing curly bracket, end the declaration with a semi-colon. After initializing the anonymous type, you can access each one of its members using the name of the variable followed by the period operator, and followed by the member variable.
Characteristics of Members of a Class#
Constants#
C# handles memory through a process called garbage collection. When you create an object with the 'new' keyword, the runtime tracks its usage and automatically frees up memory when it is no longer needed.
this Instance#
If a class contains fields and methods, the (non-static) field members are automatically available to the method(s) of the class, even fields that are private. When accessing a field or a method from another method of the class, to indicate that the member you are accessing belongs to the same class, you can precede it with the this member and the period operator. When using the this member variable (in C/C++, it is a pointer), you can access any member of a class within any method of the same class. There are rules you must observe when using this:
- The this member can never be declared: it is automatically implied when you create a class
- this cannot be used in a class A to access a member of class B
- this cannot be used in a static method
Previous Copyright © 2008-2009 C# Key Next

