Introduction to Using Classes and Objects in C Sharp

advertisement
Introduction to Using Classes and Objects in C Sharp
In the last lab session you will have had a chance to create your first web form using
the visual designer. In this session we will look at splitting the functionality of the
web form from its presentation by creating classes and ultimately a class library.
We will investigate through a number of examples the mechanism by which the web
form communicates with a class in the middle tier.
You will need to go over this material several times if you have any intention of
understanding it. There are a lot of terms and concepts covered here that must not be
skimmed over if you plan to do well with the assessments.
The following credit categories are covered in this work
Assignment 1 Credit Category 1
Assignment 1 Credit Category 2
Assignment 1 Credit Category 3
Assignment 2 Credit Category 3
Assignment 3 Credit Category 1
Assignment 3 Credit Category 2
If you completed the work for lab two then try creating the following code building
on your work so far. If you have yet to complete the previous session then you may
download the file Practice Lab 02.zip from the module web site. This contains the
code to get you started on this work.
Splitting Presentation from Functionality
One thing that we really need to consider when designing web application is to
separate the presentation layer and the functionality that drives it.
In the lecture in the first week we looked at the following possible scenario...
Presentation
(Interface)
Web browser
Middle Tier
Business
Logic
(Objects/Clas
ses)
Data Layer
Database
Presentation
(Interface)
Mobile
phone
In this diagram we see that we have a single database, a single library of middle tier
functionality and two presentation layers built on the middle tier.
In this session we will go through the steps in creating a solution which implements
the above.
If you examine the code behind Default.aspx so far we will see the following...
In order to illustrate different options for creating classes in Visual Studio we shall
look at the following:
We will create a class within the site with a single method that returns our name.
(This is exactly the same functionality as above.)
We will modify the class so that we may see both a method and a property. The
method will simply return a value. The property will have options for “get” and “set”
allowing us to pass data to and from the class allowing access to a private member
variable.
Once we have set up the class with the above facilities we will create a class library
linking this to two presentation layers.
Creating the Class
Classes may be created within Visual Studio either in a specific project / web site
(available only to that project / site) or in a class library making the classes available
to any project/site needing the functionality.
We will start by creating a class within our current site.
To do this, right click on the web site within the solution explorer and select add new
item.
From here make sure the language is set to C# and select Class.
Make sure that you give the class a suitable name (in this case clsMyName.cls) and
then press Add. Notice that it is good practice to identify the class file with the cls
prefix!
You will be asked the following question the first time you add a class to your site.
Answer yes to this and it will create a secure folder to store your classes. This is to
stop any unauthorised person simply downloading your class source code from your
web application.
This will add the new class to the solution explorer for this site in a folder called
App_Code.
There should be some code already generated for you by Visual Studio.
There are various sections to the class code that are of interest.
The top section
This section allows us to import other classes into this class. Visual Studio has a
default set of classes set up for you that it thinks you may find useful. These are
drawn from the built in .NET library.
The summary section is important to complete as it documents your class indicating
what the class does.
The main code for the class is in the following section.
Two sections of note are the class name
And the class constructor
The class name identifies the class within our code so that we may use and reference
it.
The class constructor is the section of code that executes every time we create an
instance of the class. This section of code typically contains code that initialises the
class so that it is ready to use once instantiated.
The class name and constructor name must match in C#!
Notice also the positioning of various brackets that mark out the sections of the class
code.
It takes a bit of getting used to as to which bracket marks out what. (Even as an
experienced programmer you will sometimes get it wrong.)
Set up the class so that the summary section is completed with something meaningful.
Notice the use of the commenting with three slashes “///”. This allows you to press
return without having to re-type the commenting character.
Creating Methods in a C Sharp Class
We are not going to explore too much the difference between methods and properties
in this work however the following is worth remembering.


Methods make an object do something
Properties tell us about or allow us to set the state of an object
What I want to cover here are the differences in the syntax between methods and
properties.
A method is a type of function in C sharp. To create our first method we need to
create it after the last bracket of the constructor and before the last bracket of the class
definition.
When creating a function in a class we need to decide if it going to be public or
private. A public function is accessible to code outside of the class. A private
function is only available to code within the class.
Type the following code:
The key word “public” makes the function available as a method to any code using
the class. The keyword “string” identifies the return data type of the function as
alphanumeric data. In C sharp a function of this type needs the brackets after the
name ThisIsMyName() as it may accept parameters.
Make sure you have the curly brackets to identify the start and end of the function.
Lastly you need to give the function a return value, in this case your name.
Now that we have created the functionality for our program within a class we need to
replace the code within the web form such that it uses our class.
Close and save the class file and go to the code for your web form Default.aspx.
Modify the above code so that it now uses your class as follows:
It is worth noticing that even though it has only reduced the number of lines of code
from three to two it is still a reduction. By transferring the functionality to the class
we only need to have code in our presentation layer that connects the interface to the
class.
Notice the line of code that creates an instance of the object MyNameIs.
There are quite a few things going on here.
Firstly we specify the class of the object like so...
Next we specify a name for the object we are creating based on that class...
Combined we get...
We could modify the declaration like so if we wished...
This would create a null instance of our class.
The object may not be used in a null state so in order to deal with this we must make a
call to the constructor of the class.
The “new” key word makes a call to the constructor of the class.
Either one of the following are acceptable ways of doing this...
Or
Normally we use the second syntax however there are times when we need to create a
null object and call the constructor later in our code.
Run the program to make sure that it all works correctly. You should still see your
name displayed in the text box.
This time however your name is generated by code in the class not code in the web
form.
Understanding the Constructor
The constructor of a class is an important feature of object oriented programming.
If we go back to the class code we may modify it to illustrate how the constructor
works.
Member Variables
Modify the code to declare a private member variable like so...
Declaring this variable at this section of the class (just within the bracket of the class
definition) gives it class level scope. This means its value is available to all methods
and properties we create within this class. By placing the word “private” at the front
it is not available to any code (e.g. our web form) that makes use of the class.
Also notice that we use camel case thisIsMyName with a lower case leading letter to
identify it as a member variable.
C sharp is case sensitive which means that the private member variable
thisIsMyName and the public function ThisIsMyName are two different things!
This naming convention helps us to see in our code if something is public or private.
The next step is to assign the private member variable with a value. To do this we
need to modify the constructor to include a suitable assignment operation.
Since this line of code is in the constructor. Whenever we create an instance of our
class this line of code will initialise the private member variable.
The last step is to modify our public function so that it returns the value of the
member variable.
(Notice with the use of the naming convention the code self documents.)
Compile the program and you should see that it runs exactly as before. What we have
changed is the underlying code in the class to allow us to do a few more useful things
later.
Overloading Constructors
Now that we are starting to see the role of the constructor in our class we shall see
how they may be overloaded and also illustrate how the may accept parameters.
One thing we might want to do with our class is to set it up such that it may be
initialised in different ways.
To do this we could set up a second constructor for the class, in this case one that
accepts a parameter...
Close and save your class and now modify the code for your web form like so...
By overloading the constructor we are now able to initialise objects in two different
ways.
One approach involves using a default value (Matthew Dean) via the following code...
clsMyName MyNameIs = new clsMyName();
The other allows us to pass a parameter when we create an object (Fred Bloggs)
clsMyName MyNameIs = new clsMyName("Fred Blogs");
The language looks at the number of parameters provided and selects the correct
constructor to call.
Creating Public Properties
We have so far seen how the constructor may be used to initialise a class and we have
also seen how we may pass a parameter to the constructor in order to specify
initialisation data. We have also seen how a function / constructor may be overloaded
to provide different initialisation options.
Another essential mechanism for passing data to and from objects is the use of
properties.
We have already seen properties in use on a text box. The following line of code
assigns a value to the text box’s text property...
txtYourName.Text = "Matthew Dean";
The text property controls what the user sees in the box.
Within our class it might be helpful if there were the following mechanisms in place.
1. A way to change the value of the private member variable thisIsMyName at
other times after we have called the constructor
2. A way to find out what the value of the private member thisIsMyName is
Why Not Just Make Everything Public?
One very good question at this point is to ask “why not simply change the member
variable from private to public?”
Like so...
We could do this however it would create a problem later on in our programs.
If we make the member variable public we may then set its value in the web form like
so...
clsMyName MyNameIs = new clsMyName();
MyNameIs.thisIsMyName = "Jim Jones";
This obviously allows us access to the variable.
However what if we wanted to change the logic of the class so that first and last name
were stored in separate member variables and we get rid of thisIsMyName?
Any code in web forms accessing the member variable would need to be changed.
Not so bad if we only have a single web form, but if we have dozens, each accessing
the variable multiple times it will create major maintenance problems.
In order to get round this problem we incorporate data hiding and encapsulation.
Data Hiding
In order to hide the data in this case we need to change the declaration of
thisIsMyName back to private. This hides the data in the class from any code that
creates objects based on it.
Encapsulation
The next step is to create an interface allowing access to this data. This is where our
public properties come in. Add the following code to your class definition.
This declares a public property called MyName which accepts/returns a value of
string data type.
To make use of the property and access the value of thisIsMyName you could modify
the code in your web form as follows.
Irritating Points of Syntax
Notice in the declaration of the property there is no option to add parameters (i.e. no
brackets)
This is a signal to the language that you have created a property and not a function.
Functions in C sharp accept parameters, properties do not!
Also notice that when we make use of the property in the presentation layer code
there are no brackets there either...
If it was a method then you must add brackets even if there are no parameters.
The Benefits of Encapsulation
What we will do now is modify the class to demonstrate the real benefits of
encapsulation.
The first step is to remove the member variable thisIsMyName and replace it with two
new private member variables
//private string firstName
private string firstName;
//private string lastName
private string lastName;
Doing this should create some errors in your class that will need to be fixed.
Modify the constructor with no parameter as follows...
//this constructor sets a default value
public clsMyName()
{
//initialise firstName and lastName
firstName = "Matthew";
lastName = "Dean";
}
We have a problem to consider with the other constructor though. The second
constructor accepts a single parameter with the value of a person’s full name.
One thing we want to avoid if at all possible is changing the properties and methods
of the class. This means that the inner workings of the class may change however the
code that calls the class should not change.
Add at the end of your class the following private void function.
Making it void means that it doesn’t return a value. Making it private means that it is
hidden from any code that uses the class.
Now modify the second constructor (the one that has a parameter) like so...
This code makes a call to our private void function which takes a full name and splits
it into first name and last name.
You will next need to modify the public function ThisIsMyName
And the code for your public property MyName
If you have done all of the above correctly you should be able to build and run your
site.
Now here is the important point to what we have done.
In the above work you have made significant changes to the inner workings of your.
Now because these workings are hidden inside the class they are encapsulated. Some
things that we didn’t change are the methods and properties the web form uses to
communicate with the class.
Encapsulation means that we do not need to change the code in the web form when
we re-write the class!
Creating the Class Library
We have covered a large number of concepts above and we have gone a long way in
splitting the functionality from the presentation. The next step is to make the class
available to other sites / projects within the solution.
To do this we need to create a class library.
To create a class library in Visual Studio right click on the solution in the solution
explorer and select new project...
You will see the following screen
Make sure...




You select C# as the language for the library
You select class library from the central list
You enter a suitable name for your library (MyCLassLibrary in this example)
That you set the location to the path of your solution on the file system
Once you are sure this is all correct then press OK.
You should see the new class library added to the solution explorer.
Visual Studio will create for you a sample class. Notice that the code is a little
different to the class we created in our web site.
Namespaces
We have a new entry in the structure of the class definition, the namespace.
A namespace allows us to organise our classes into logical groups and also avoid
confusion.
For example you might have a program to monitor bus routes with a class called bus.
You may also have another program to record computer hardware also with a class
called bus.
To distinguish between the two you might set up a transport namespace and a
computer hardware namespace.
Within this module we shall keep the namespace as the name of the class library.
To modify this default class select all of the code, delete it and then copy and paste
the code from your first class into this new class.
You will then need to add the class code to the namespace for your library.
Don’t forget the curly bracket after the namespace declaration and the other one right
at the end of the class.
Also make sure that you rename the class file name in the solution explorer.
Now that your class is in the class library you may delete the original class file in the
web site.
(Or you could exclude it from the project if you wanted to keep a copy of the file!)
If you build and run your solution you should see an error.
It is worth pointing out at this stage that the answer to that question is always NO! If
you press yes Visual Studio will run the last working version of your code, not the
code you are currently editing.
The problem we now have is that since we deleted our original class file the new file
in the library is not linked up to the web form.
When the class library is built it compiles to a file called a dynamic link library
(DLL). This DLL needs to be incorporated into your web site so that the class’s
features are available to your site.
To do this right click on your web site and select add reference.
The class library should be listed.
Press OK and the DLL from your class library will be copied to your site. (Every time
you compile your solution this fill is updated.)
You now need to modify the code in your web site to reference the class library
correctly like so...
Or you could simply add a reference to you library at the top of the web form. In that
case you don’t need to reference the library every time you use it.
Creating a Second Presentation Layer
Just to prove that it all works do the following.




Create a new web site within your solution
Create a new default page for the site
Link the class library to the new site
Create a second interface that uses the class library in a different way
Note, to make this new web site the start up project you will need to right click on the
site and select “set as start-up project”.
Associated Concepts
Terms and concepts to understand
 Classes
 Objects
 Methods
 Properties
 .NET Library objects
 Constructors
 Naming conventions for classes
 Passing parameters
 Overloading functions
 Public & Private - Data hiding
 Instantiation
 Null objects
 Member variables - naming convention
 Encapsulation
 Class libraries
 Namespaces
 Dynamic Link Libraries
Using the debugger in Visual Studio
Download