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.
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;
}
|
|
Search Engine Optimization
 
Syndication Viewer
Our Web host:
IX WebHosting
|