Sams Teach Yourself C# in 24 Hours

Sams Teach Yourself C# in 24 Hours

By James Foxall and Wendy Haro-Chun

Creating Class Members

Other languages, such as Visual Basic, differentiate between class methods and public methods that are globally available outside of a class. C# requires all methods to exist in the context of a class, but a globally available method can be achieved by defining static methods in your class. Static methods are always available regardless of whether an instance of the class exists. In fact, you can't access a static member through an instance of a class, and attempting to do so results in an exception (error).

Although you could place all your program's code into a single class module, it's best to create different modules to group different sets of code. In addition, it's best not to place code that isn't specifically related to a form within a form's class module; place such code in the logical class or in a specialized class module.

One general rule for using static members is that you should create classes to group related sets of code. This isn't to say you should create dozens of classes. Rather, group related methods into a reasonably sized set of classes. For instance, you might want to create one class that contains all your printing routines and another that holds your data-access routines. In addition, I like to create a general-purpose class in which to place all the various routines that don't necessarily fit into a more specialized class.

Start C# now and create a new Windows Application project named Static Methods.

Change the name of the default form to fclsExample, set its Text property to Method Example, and set the Main() entry point of the project to reference fclsExample instead of Form1. Change the Size property of the form to 371, 300. Next, add a new class to the project by choosing Add Class from the Project menu. C# then displays the Add New Item dialog box, as shown in Figure 11.1.

11fig01.jpg

Figure 11.1 All new project items are added using this dialog box.

Note that this is the same dialog box used to add new forms. Change the name of the class to clsStaticExample.cs and click Open. C# then creates the new class and positions you in the code window—ready to enter code (see Figure 11.2).

11fig02.jpg

Figure 11.2 Classes have no graphical interface, so you always work with them in the code editor.

Save your project now by clicking Save All on the toolbar.

Share ThisShare This

Informit Network