This tutorial shows you how to use a class so that multiple forms can use your methods. C# version.

Using classes in your Windows Applications not only makes it easier to organize our code, but it also makes it easier to maintain our code. With classes, we can store our methods in one place and use them many times on several Windows Forms (or web pages). Furthermore, when it comes to editing our methods, we only need to edit them in one place – the class.
In this tutorial, we will look at how we can create a class, how we can create methods within that class and also how we can make use of the class in a Windows Form by calling its methods.

The first thing we will do is to create a new project in Visual Studio. This example was created with VS .NET 2008, but the principles apply to 2005 as well. Once we have our project open, we will right-click it in Solution Explorer and choose Add > Class (Or Add New Item, Class). You can name it whatever you want, in this example, we left the default – Class1.

We should then be provided with the default code of the class, which should look something like this:

Notice that the namespace is the Project Name, and within that is the class. Now if we goto the code of our Form1, by right-clicking it and choosing View Code, we will see the following:

Notice that the Form1 is also wrapped in the namespace. We are going to create three methods in the class that this form will use, so we will add the following controls to our form: Simple Addition – two labels, two textboxes and a button; Fahrenheit to Celsius – one textbox, one button and one label; Celsius to Fahrenheit – one textbox, one button and one label. The labels will be used to display the results of the methods; you can add more labels to give titles if you wish.

Once we have added these controls to our form, we can begin coding. Let’s go back to our class and create our methods. They are very simple methods to show how classes work:

In these methods, we are performing simple calculations to provide functionality to the user, which we are doing with a class.
These methods reside in the Class1 we created, which is in a separate file to our Form1 code. To utilize these methods, we will need to reference the Class name in our Form1 code, like so:

Notice that we are simply referencing the Class name first, and then the method. We can do the same for the other methods, and also add a try and catch to each of them to catch any errors:

The entire code-behind of Form1 will look something like this:

Download Source Files