Braintique.com header
Left Navigation Bar

Adding a Class and Method

There are a number of ways to add a class module to a C# project. One is to open the Add New Item dialog (by selecting Add Class from the Project menu). In the Add New Item dialog make sure that Class is selected in the Templates pane, and click Open.

Add New Item

The new bare-bones class, with a class constructor and nothing else, will look like this (for clarity, I’ve removed the auto-generated comments):

using System;
namespace Builder2
{
public class Class1
{
public Class1()
{

}
}
}

Lets add a method to this class that checks to see if the number passed to it is a prime (for an explanation of the prime number checking algorithm, please see my book Visual C# .NET Programming) :

using System;
namespace Builder2
{
public class Class1
{
public Class1()
{

}
public void IsPrime (long NumToCheck ) {
for (long i =2; i <= Math.Sqrt(NumToCheck); i++) {
if (NumToCheck%i == 0 ) {
// not a prime
return;
}
}
// is a prime, fire the event
return;
}
}
}

We’re going to call the event that is fired when a prime number is found OnPrime. Here’s how the IsPrime method looks with the OnPrime event fired (note that the event passes the prime number found as a parameter):

public void IsPrime (long NumToCheck ) {
for (long i =2; i <= Math.Sqrt(NumToCheck); i++) {
if (NumToCheck%i == 0 ) {
// not a prime
return;
}
}
// is a prime, fire the event
System.EventArgs p = new System.EventArgs();
OnPrime (this, p, NumToCheck);
return;
}

Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write