Click here to download the source code for this lesson.
In the previous lessons about User defined Classes we had created a Class called Arithmetic that was able to add numbers. In this lesson we will talk more about User defined Classes and using them to store information (i.e. store state) so that the information can be passed around between different parts of your application. One of the strengths of the C# language is that it is Object-Oriented and one of the benefits of Object-Oriented languages is the ability to encapsulate data in objects.
For this example I created a web page called Default.aspx that has 3 pieces of information that the user can input: first name, last name and age; each in separate TextBox controls. If I wanted to create a Method in my web application that will take this information and do something with it (e.g. save it to a database), I would need a way to pass that information to the Method. I could declare a Method that takes 3 parameters and pass the information that way, however this is not a very Object-Oriented solution and if I wanted to change the parameters or add new parameters in the future, it would require changes to the Method declaration and the code that calls the Method. A more robust approach is to create a User defined Class to store the information and pass around the Class.
I created a Class called Customer that will encapsulate the 3 data elements:
public class Customer { string mFirstName; string mLastName; string mAge; public Customer(string pFirstName, string pLastName, string pAge) { mFirstName = pFirstName; mLastName = pLastName; mAge = pAge; } public string getFirstName() { return mFirstName; } public string getLastName() { return mLastName; } public string getAge() { return mAge; } }
Notice that the 3 pieces of information are stored as instance variables in the Class Customer. In my web application I am able to store the information in an Object of this Class with one line of code and pass it to a Method called DisplayCustomerInformation as follows:
Customer mycustomer = new Customer(txtFirstName.Text, txtLastName.Text, txtAge.Text); DisplayCustomerInformation(mycustomer);
Notice that I passed the values of the 3 TextBox controls to the Customer constructor. Then I passed the variable mycustomer to a Method that displays a summary of all the values in a multiline TextBox control. Although this is a simple example, you can experiment with passing around User defined Classes in your applications. You can use them just like regular C# variables. I recommend using User defined Classes as much as possible to help keep your program more maintainable and Object-Oriented.