Classes Fundamentals
|
Introduction
|
To use a variable, we can declare it using either var
keyword or a known and simple data type. For example, we can use an integer
to declare a variable that represented the number of bedrooms of a house.
Here is an example:
|
|
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click File -> New Project
- In the middle list, click Empty Project
- Change the Name to DepartmentStore1
- Click OK
Like a variable, a class must have a name. The name
primarily follows the same rules
as the variables. You can then add your own rules. In our lessons:
-
If the name of a class is in one word, the first letter will be in uppercase. Examples are Identification, Vehicle, or Student
-
If the name of a class is a combination of words, the first letter of each word will be in uppercase. Examples are DrivingRecord, GeometricShape, or SocialSecurityInformation
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 rename a class (or one of its members) or to easily
navigate to a class.
The Class View
|
Probably the best window to manage classes is called the
Class View. To get the Class View:
- If the Class View is not yet displaying, on the main menu, you can click View -> Class View
- If the Class View is showing already, click its tab
The Class View is made of six sections. The title bar
and the use of the Class View follow the same description as for the
Solution Explorer:
The second part of the title bar is its toolbar
.
The Class View New Folder button allows you to create
and add a new folder to the project. The Back and the Forward buttons allow
you to navigate among the classes.
Under the toolbar, there is another bar made of a combo
box and a button. These allow you to search.
The body of the Class View is made of two sections. The
first node of the upper section displays the name of the project. Under the
project node, the names of classes display. The bottom section of the Class
View is used to display the members of a class. To see the members of a
class, you can click it in the top window. Here is an example:
There are various ways you can create a class. If you
are working from a text editor, start a file, type class, followed by a
name, and followed by curly brackets. Here is an example of a class named
House:
class House { }
From your text editor, save the file with the extension
.cs. The name of the file doesn't have to be the same as the class. You
should save the file in the same folder that contains the other files of the
same project.
A class is created in a code file. As such, you can
include it in the first file of your project. Here is an example:
class House
{
}
class Exercise
{
static void Main()
{
int bedrooms = 3;
}
}
|
|
If you are creating your project using Microsoft Visual
C# 2010 Express or Microsoft Visual Studio, it can assist you with creating
a class. In Lesson 1, we saw how
to create a code file. After creating one, you can just type the code
for the class. When you use the Add New Item option from the main menu or
from the Solution Explorer, you can select any type of file you want to
create, including a class. Otherwise, you can explicitly indicate that you
want to create a class. This would automatically select the Class option in
the Add New Item dialog box.
To create a new class:
- On the main menu, click Project -> Add Class... (or Project -> Add New Item... In the middle list of the Add New Item dialog box, click Class)
- In the Solution Explorer, right-click the name of the project, position the mouse on Add, and click Class...
- In the Class View, right-click the name of the Project, position the mouse on Add, and click Class...
Any of these actions would display the Add New Item
dialog box with the Class option selected. If you had selected the Add New
Item from the main menu or the Solution Explorer, you can click Class. In
the Name text box, accept or change the default name and click Add. A new
file named after the class with the .cs extension would be added to your
project.
You can also use skeleton code to start a class:
- In the section of the Code Editor where you want to add the class,
right-click and click Insert Snippet... Double-click Visual C#. In the
list that appears, double-click class
- If you had already written code, such as declaring some variables,
and you want to include that code in a new class, select that code.
Right-click it and click Surround With...
In the list that appears, double-click class:
A class with the default name MyClass would be added.
You can accept that name or change it.
|
- On the main menu, click Project -> Add New Item...
- In the middle list of the Add New Item dialog box, click Code File
- Change the name to StoreItem
- Click Add
- In the file, type the following:
class StoreItem { }
- On the main menu, click View -> Solution Explorer
- To create another code file, in the Solution Explorer, right-click DepartmentStore1, position the mouse on Add and click New Item...
- In the middle list of the Add New Item dialog box, click Code File
- Change the name to DepartmentStore
- Click Add
- In the empty document, type the following:
class DepartmentStore { static void Main() { } }
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:
- In the tabs section of the Code Editor, click the tab that represents the file in which the class exists. Then, in the left combo box of the Code Editor, select the class
- In the Solution Explorer, under the name of the project, double-click the name of the file that contains the class. If the file contains more than one class, in the left combo box of the Code Editor, select the class
- In the Class View, under the name of the Project, double-click the name of the class
- In the Class View combo box, right-click the class and click Go To Definition
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 your text editor
or 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 from either
Microsoft Visual C# 2010 Express or Microsoft Visual Studio, it provides a
better solution and would take care of everything behind the scenes.
To rename a class in Microsoft Visual C# or Microsoft
Visual Studio:
- In the Code Editor, right-click the name of the class, position the mouse on Refactor, and click Rename...
- In the Class View, right-click the name of the class and click Rename...
- In the Class View, click the name of the class to select it. On the main menu, click Refactor -> Rename...
Any of these actions would display the Rename dialog
box. In the New Name text box, type the desired name or edit it. Use the
check boxes to indicate whether you want the Code Editor to change the name,
if used, in the comment and the strings. When you are ready, click OK. This
would display the Preview Changes - Rename dialog box that shows the various
parts where the name is used. When you have checked everything, if it suits
you, click Apply.
C# Language Accessories
|
When C# was invented, one of its biggest goals was to
avoid some of the difficulties of C/C++. Among them was the use of pointers.
C/C++ uses pointers to refer to the area in memory where a value is located.
C# highly avoids pointers and takes over memory management as opposed to
letting the programmer take care of that aspect of an application. You can
still use pointers in C# in extreme cases when you judge them necessary.
Because the C# compiler is in charge of managing the
memory used by the values of an application, pointers are said to be unsafe.
If you want to use a pointer in your application, you must precede the name
of every method that uses unsafe code with the unsafe keyword. Here
is an example:
class Exercise
{
unsafe static void Main()
{
int Length = 224;
int *Len = &Length;
System.Console.Write("Length ");
System.Console.WriteLine(Length);
System.Console.Write("Length ");
System.Console.WriteLine(*Len);
System.Console.WriteLine();
Length = 804;
System.Console.Write("Length ");
System.Console.WriteLine(Length);
System.Console.Write("Length ");
System.Console.WriteLine(*Len);
}
}
To compile the application, you must indicate that you
are using unsafe code. To do that, use the /unsafe modifier. Here is
an example:
csc /unsafe Exercise.cs
To apply this option in Microsoft Visual Studio, on the
main menu, you can click Project -> Project Properties... In the
Build section, click the Allow Unsafe Code check box:
Region Delimiters
|
Microsoft Visual Studio provides various techniques to
assist you with code writing and management. The characteristics include
color-coded words, intuitive indentation, the IntelliSense, delimitation of
sections of code, etc. Consider the following contents of the Code Editor
based on what we have reviewed so far:
Notice that there are - buttons on the left side of some
lines of code. These allow you to collapse a section of code if you think
you don't need to see it. To do this, you can click the - button. If you
click that - button, it changes into a + button. Here is an example:
The + button allows you to expand a hidden code section.
This behavior of creating + and - buttons is part of the Code Editor of
Microsoft Visual Studio (yes, many other programming environments use that
behavior also). To create these sections, the Code Editor follows some
rules. For example, it looks for the start and end of such an item as a
classes (or other items we will study in other lessons).
Besides, or instead of, the sections of code created by
the Code Editor, if you want, you can create your own sections. To create a
section:
- If you are working in a text editor, in the
Code Editor of Microsoft Visual C# 2010 Express, or in Microsoft Visual
Studio, start the section in the file with:
#region Whatever
and end it with
#endregion Whatever
- If you are working in Microsoft Visual C# 2010 Express or in
Microsoft Visual Studio:
- If you want to create a section with an empty section, right-click the line where you want to start the region and click Insert Snippet... Double-click Visual C#. In the list, double-click #region
- If you want to create a section that includes code already,
select that code in the Code Editor. Right-click the selected
section and click Insert Snippet...
Double-click Visual C#. In the list, double-click #region. A region with a default name would be created:
When and where you start a region, the #region
expression is required. On the right side of this expression, you can type
anything you want on the line. To end the section, type #endregion,
followed by anything you want. Consider the following example:
class Circle { } #region This section is reserved for quadrilateral shapes class Rectangle { } class Square { } #endregion This is the end of the quadrilateral section class Line { }
You don't have to type anything on the right side of
#endregion. After creating the region, the Code Editor would display a -
button to the left side of #region with a line from there to the left
of #endregion:
This then allows you to expand and collapse that section
at will:
We mentioned that you didn't have to type anything on
the right side of #endregion and you could leave it empty. In our
example, notice that there is a rectangle with gray lines around the string
that follows #region. This rectangle doesn't cover the string that
follows #endregion. This means that if you don't type anything on the
right side of #endregion, that section on the right side the
#region line would not show.
Introduction to Using a Class
|
Like any normal variable, to use a class in your
program, you can 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.
Like the variables we introduced in Lessons 3 and 4, 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:
class House
{
}
class Program
{
static void Main()
{
var property . . .
}
}
Or the following:
class House
{
}
class Program
{
static void Main()
{
House property;
}
}
In Lessons 3 and 4, we saw how to declare variables of
regular types. We also mentioned that, when such variables are initialized,
the compiler stores their values in the memory area it had previously
reserved. The data types used for such variables are called value types. To
store their values, the compiler creates a memory area named a stack. The
other area is named the heap. This is reserved for variables declared for
classes:
When you declare a variable using a class, you must ask
the compiler to allocate memory for it, on the heap. To make this request,
you use an operator called new. Here is an example:
class House
{
}
class Program
{
static void Main()
{
var property = new House();
}
}
Instead of the var keyword, you can
declare the variable using the name of the class. As mentioned for value
types, if you use the var keyword, you must allocate memory immediately. If
you use the name of the class, you can declare the variable on one line,
then use the new operator on another line to allocate memory for it. Here is
an example:
class House { } class Program { static void Main() { House property; // You can do something here property = new House(); } }
In C#, as well as Visual Basic, 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.
|
- In the body of Main, type the following:
class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); } }
When you need to use the values and behaviors that a
class offers, we saw that you must declare a variable for it. We also saw
that you should provide the values for the field(s) of the class before
using it. This allows the compiler to fill the memory reserved for that
variable with the desired value(s). Sometimes, when declaring the variable,
you may not be ready to provide the necessary values for the variable.
A variable that has been declared for a class but that
has not yet received values for its fields in referred to as a null object.
To create a null object, when declaring the variable use the name of the
class, followed by a name for the variable, and assign the null
keyword to it.
In our introduction to primitive data types, we saw
that, to indicate that a variable cab hold a null value, you can add a
question mark to it. If you are using a class, don't add a question mark to
the name of the class. Here is an example:
class House
{
}
class Program
{
static void Main()
{
House property = null;
}
}
If a variable of a class was previously declared and
initialized but, one way or another, the values have been removed or
deleted, the variable is also referred to as a null object. Most of the
times, you will only be interested to find out whether an object is null.
Unlike its parents 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 F#. 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 Exercise
{
static void Main()
{
var number = 244;
var thing = "Vehicle";
System.Console.WriteLine(number);
System.Console.WriteLine(thing);
}
}
|
- On the main menu, click View -> Class View
- In the Class View, double-click DepartmentStore1 to expand it
- In the top section of the body of the Class View, right-click StoreItem and click Go To Definition
- Press Home, type public and a space to change the
document:
public class StoreItem { }
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.
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. These parts are created as member
variables. In C#, a variable created in the body of a class is called a
field. Each field is declared as normal variable with a name and a data
type. The name of a variable follows the same rules we reviewed for
names of variables.
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; }
If you want to indicate that a field of primitive type
can hold a null value, you can add a question mark to it. Here are examples:
public class House { string propertyNumber; char? propertyType; byte? stories; uint? bedrooms; decimal? value; }
If you use this technique, there are rules you must
observe after that.
The variables declared in the body of a class are
referred to as its member variables and each member variable is referred to
as a field. The fields can be any type we have seen in the previous lesson.
When creating a class, it is your job to decide what your object is made of.
|
New Convention:From now on, in our lessons, to refer to a field that belongs to a class, we may writeClassName.FieldNameThis means that we are referring to the field FieldName that is a member of the class ClassName. |
- Change the StoreItem class as follows:
public class StoreItem { long itemNumber; string itemName; string size; decimal unitPrice; }
Access Modifiers of Class 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.
The parts of a class that must be hidden 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 decimal value; }
|
- Change the StoreItem class as follows:
public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; }
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 | internal | private | |
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 | Yes | No |
Objects outside of this program can access this member | Yes | No | No |
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 saw earlier. 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:
public class House { internal long propertyNumber; internal string propertyType; internal uint bedrooms; internal double value; } |
|
public class Exercise { static void Main() { var property = new House(); property.propertyNumber = 283795; property.propertyType = "Single Family"; property.bedrooms = 4; property.value = 652880; } }
Remember that the primitive types can use a question
mark:
public class House { internal long? propertyNumber; internal string propertyType; internal uint? bedrooms; internal double? value; } public class Exercise { static void Main() { var property = new House(); property.propertyNumber = 283795; property.propertyType = "Single Family"; property.bedrooms = 4; property.value = 652880; } }
Once a field has been initialized, you can use the
period operator to access it and retrieve its value:
public class House { internal long? propertyNumber; internal string propertyType; internal uint? bedrooms; internal double? value; } public class Exercise { static void Main() { var property = new House(); property.propertyNumber = 283795; property.propertyType = "Single Family"; property.bedrooms = 4; property.value = 652880; System.Console.WriteLine("=//= Altair Realtors =//="); System.Console.WriteLine("Properties Inventory"); ; System.Console.Write("Property #: "); System.Console.WriteLine(property.propertyNumber); System.Console.Write("Property Type: "); System.Console.WriteLine(property.propertyType); System.Console.Write("Bedrooms: "); System.Console.WriteLine(property.bedrooms); System.Console.Write("Market Value: "); System.Console.WriteLine(property.value); } }
This would produce:
=//= Altair Realtors =//= Properties Inventory Property #: 283795 Property Type: Single Family Bedrooms: 4 Market Value: 652880 Press any key to continue . . .
|
|
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. Here is an example:
public class Exercise
{
static void Main()
{
var BookInformation = new
{
Title = "Calculus 6e Edition",
Pages = 1074,
Cover = "Hard Back"
};
}
}
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. Here is an example:
public class Exercise { static void Main() { var BookInformation = new { Title = "Calculus 6e Edition", Pages = 1074, Cover = "Hard Back" }; System.Console.WriteLine("=//= BookInformation =//="); System.Console.Write("Title: "); System.Console.WriteLine(BookInformation.Title); System.Console.Write("Nbr of Pages: "); System.Console.WriteLine(BookInformation.Pages); System.Console.Write("Type of Cover: "); System.Console.WriteLine(BookInformation.Cover); } }
This would produce:
=//= BookInformation =//= Title: Calculus 6e Edition Nbr of Pages: 1074 Type of Cover: Hard Back Press any key to continue . . .
Remember that spreading the declaration on many lines
only makes it easy to read. Otherwise, you can as well include everything on
the same line.
public class Exercise
{
static void Main()
{
var book = new { Title = "Calculus 6e Edition", Pages = 1074 };
System.Console.WriteLine("=//= BookInformation =//=");
System.Console.Write("Title: ");
System.Console.WriteLine(BookInformation.title);
System.Console.Write("Nbr of Pages: ");
System.Console.WriteLine(BookInformation.pages);
}
}
Managing the Fields of a Class
|
Introduction
|
To assist you with managing the fields of a class, the
Code Editor is equipped with two combo boxes.
The left combo box displays the classes that are inside
of the current file. The right combo box displays the members of the class
that is selected in the left combo box:
Accessing a Field
|
There are many ways you can access a field:
- Open the file that contains the class and visually locate the field in the file
- Open the file that contains the class. On the main menu, click Edit -> Quick Find. Type the name of the field and click Find Next. This approach assumes that you know precisely the name of the field you are looking for
- In the upper section of the body of the Class View, click the name of the class that contains the field. Its list of members will appear in the lower side of the body. You can then double-click it
- In the upper section of the body of the Class View, click the name of the class that contains the field. In the lower section of the Class View, right-click the name of the field and click Go To Definition
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, you can click Edit -> Quick Replace, 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 C# or Microsoft
Visual Studio:
- Open the file that contains its class. Either press Ctrl + H or, on main menu, click Quick Replace. In the Find What combo box, type the name of the field, and click Replace All
- Open the file that contains its class. Click the field to position the caret in it. Press Ctrl + H or, on main menu, click Quick Replace. In the Find What combo box, make sure the name of the field is entered and click Replace All
- In the upper side of the Class View, click the name of the class. In the lower part, right-click the field and click Rename... In the New Name text box of the Rename dialog box, enter the desired name for the field. Use the check boxes to specify whether you also want the name to be edited in the comment and the strings. Once you are ready, click OK. In the Preview Changes - Rename dialog box, see the list of all parts where the field is used. If everything is alright, click Apply.
|
- Close your programming environment
- When asked whether you want to save, click No
No comments:
Post a Comment