Thursday, February 17, 2011

Simple C# Class Example

Simple C# Class Example



using System;
public class myCalc
{
private int result;
//constructor without a parameter defaults to 0
public myCalc()
{
result = 0;
}
//constructor with parameter
public myCalc(int x)
{
result = x;
}
//destructor
~myCalc()
{
result = 0;
}
//methods
public void displayResult()
{
Console.WriteLine("Result = {0}", result);
}
public void add(int x)
{
result = result + x;
}
public void subtract(int x)
{
result = result – x;
}
}
class myTest
{
public static void Main()
{
myCalc mC = new myCalc(90);
mC.displayResult();
mC.add(45);
mC.displayResult();
mC.subtract(35);
mC.displayResult();
mC.subtract(110);
mC.displayResult();
}
}
///////////////////////////////////////////////
///////////////////////////////////////////////
Output
******
Result = 90
Result = 135
Result = 100
Result = -10

0 comments: