Home Page

Click here to download the sample source code for this Calling User defined Classes lab exercise 

This exercise is a continuation of Creating User defined Classes.  In that lesson, we practiced creating a new Class and we put a Method in the class called AddTwoNumbers.  Now let’s see how to actually use that Class by calling the Method from our ASP.NET web page Default.aspx.  Open Default.aspx and go to the Design view.  Drag a Button and a TextBox onto the web form and change the Text property of the Button to say “Call User defined Class”.  Double click the Button to create the event handler and put:

 

Arithmetic mynewclass = new Arithmetic();
int iResult = mynewclass.AddTwoNumbers(50, 20);
TextBox1.Text = iResult.ToString();

In order to call a Class you first have to Instantiate an  of the Class.  This terminology means that you have to declare a variable with the type set to your Class name.  In the above example, notice that I did that “Arithmetic mynewclass”.  mynewclass is a variable of type Arithmetic.  The second part of instantiating an Object is to apply the “new” keyword after the assignment operator “= new”.  Finally, the last step is to put the Class name again with open and closed parentheses “Arithmetic()”.

Once you do this instantiation, you can then call the Methods that are available in the Class.  Creating your own Class is sometimes referred to as Creating a User Defined Type since a Class is a type in C#.  Notice earlier I said that mynewclass is a variable of type Arithmetic.  Arithmetic is a User Defined Type.  In order to call a Method that is inside the Class all you have to do is use the variable that you declared (in my case mynewclass) and put a . (period) after it followed by the Method name “mynewclass.AddTwoNumbers”.  Then you can pass parameters to the Method inside parentheses.  Since the Method AddTwoNumbers returns an Integer, I declared a variable to store the result of the Method call.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment