syntax classes in c# code example
Example: 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
}
}
}