how to make 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: c# class declaration
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
Example 3: how to make a object in c#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Other properties, methods, events...
}
class Program
{
static void Main()
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
// Declare new person, assign person1 to it.
Person person2 = person1;
// Change the name of person2, and person1 also changes.
person2.Name = "Molly";
person2.Age = 16;
Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/*
Output:
person1 Name = Leopold Age = 6
person2 Name = Molly Age = 16
person1 Name = Molly Age = 16
*/