Home Page

Click here to download the sample source code for this User defined Classes lab exercise  If you forgot how to open the files using Visual Web Developer, click here to learn How to open C# ASP.NET Website files.  Please use these files only as a reference.  You should go through the exercises yourself and create your own project according to the instructions in the exercise. 

Now that we have seen how C# Methods are declared and used, it’s time to move on to .  A User defined Class is a way to group a set of related Methods and variables together.  Just like Methods, Classes are a good way to further organize and reduce redundancy in your program’s soure code.  In C#, almost everything is built around Classes, even some of the language data types such as String, which is actually a Class called .

Let’s take one of the Methods “AddTwoNumbers” we had created in the prior exercise “Creating and using Methods” and move it into a new Class.  Create a new website using Visual Web Developer and call the project Lab5.  In the Solution Explorer, right click the project name and choose “Add New Item”.  From the templates list, choose “Class” and then enter “Arithmetic” for the name of your new Class.  Click Add to finish.  Click here to watch a sample video on how to Create a new Class.

Notice that Visual Web Developer will create an empty Class for you and there is only one Method in the Class right now.  That Method is named “Arithmetic” and notice that it has the same name as the Class itself.  This is a special Method called the Constructor.  More about Constructors in another lesson.  Underneath the Constructor Method Arithmetic, put the following new Method:


public int AddTwoNumbers(int iNum1, int iNum2)
 return iNum1 + iNum2;

Make sure that you put the code after Arithmetic and NOT inside it.  You should now have 2 methods in your Class: Arithmetic and AddTwoNumbers.  A Class can contain as many Methods as you like, generally all of the Methods in a particular Class should be related in some way.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment