1. Computing & Technology

Discuss in my forum

C# Programming Tutorial - Programming Winforms in C#

By , About.com Guide

8 of 10

Using Your Classes in Forms
C# Quadratic Equation solver
Say you've got a class that solves quadratic equations of the form y = Ax2 + Bx + C = 0. This tells you where a quadratic curve intersects the horizontal axis (when y=0). You set the properties a,b,c in your class, call the CalcRoots method and then can access the PlusRoot and the MinusRoot proprties. For example if a is 4, b is -9 and c is 5. Then 4x2 -9x + 5 =0. The answers are 1.25 and 1.

Right Click on the Solution Explorer. If you can't see this click the View Menu then View Solution Explorer. Right click on ex1, Add then Add New Item, select Class and name it as QuadraticSolver. This is an empty class called QuadraticSolver with three int private fields (a,b,c ) and three write only (set ) properties A,B and C as well as two fields plusroot and minusroot and two readonly properties PlusRoot and MinusRoot. The method CalcRoots() returns true or false according to whether it can solve the quadratic without a divide by zero or complex answer.

There are five TextBoxes, a button and a label inside a GroupBox. This holds other controls inside a bordered frame, useful for structuring the form and keeping related controls together. Clicking the Solve button reads the three input parameters (a,b,c ) calls QS.CalcRoots(). QS is the instance of the class QuadraticSolver. If the CalcRoots method call fails then it's because the Error property has been set so this is displayed instead of the two roots.

It can be quite instructive to read the code generated by the form designer. Note that code is only generated to set a property value that differs from the default. Searching for System.EventHandler in the file reveals all of the event handlers; the alternative is to look through at each control which is fine for a small number but tedious otherwise.

On the next page : Reading the Code Continued

©2012 About.com. All rights reserved.

A part of The New York Times Company.