how to implement a class in c## code example
Example 1: class in c#
public class Car
{
// fields
public bool isDriving = false;
// constructor
public Car( string make )
{
Make = make;
}
// properties
private string _make = string.Empty;
public string Make
{
get { return _make; }
set { _make = value; }
}
// methods
public void drive()
{
if( isDriving )
{
// Car is already moving
}
else
{
// start driving the car
isDriving = true;
}
}
public void stop()
{
if( isDriving )
{
// stop the car
isDriving = false;
}
else
{
// car is already not moving
}
}
}
// ---
// An example of using this class in a console app
using System;
public class Program
{
public static void Main()
{
// construct a new class of type Car and set the Make
// property to "VW" using the constructor.
Car newCar = new Car( "VW" );
// display the make of our new car
Console.WriteLine( newCar.Make );
// call the drive method of the car class
newCar.drive();
// display the value of the isDriving property to
Console.WriteLine( newCar.isDriving );
// call the stop method of the car class
newCar.stop();
// display the value of the isDriving property
Console.WriteLine( newCar.isDriving );
}
}
// the class
public class Car
{
// fields
public bool isDriving = false;
// constructor w
public Car( string make )
{
Make = make;
}
// properties
private string _make = string.Empty;
public string Make
{
get { return _make; }
set { _make = value; }
}
// methods
public void drive()
{
if( isDriving )
{
// Car is already moving
}
else
{
// start driving the car
isDriving = true;
}
}
public void stop()
{
if( isDriving )
{
// stop the car
isDriving = false;
}
else
{
// car is already not moving
}
}
}
Example 2: how to call a method from a class in c#
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args) {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}