class and object in c# code example
Example 1: class in c#
public class Car
{
public bool isDriving = false;
public Car( string make )
{
Make = make;
}
private string _make = string.Empty;
public string Make
{
get { return _make; }
set { _make = value; }
}
public void drive()
{
if( isDriving )
{
}
else
{
isDriving = true;
}
}
public void stop()
{
if( isDriving )
{
isDriving = false;
}
else
{
}
}
}
using System;
public class Program
{
public static void Main()
{
Car newCar = new Car( "VW" );
Console.WriteLine( newCar.Make );
newCar.drive();
Console.WriteLine( newCar.isDriving );
newCar.stop();
Console.WriteLine( newCar.isDriving );
}
}
public class Car
{
public bool isDriving = false;
public Car( string make )
{
Make = make;
}
private string _make = string.Empty;
public string Make
{
get { return _make; }
set { _make = value; }
}
public void drive()
{
if( isDriving )
{
}
else
{
isDriving = true;
}
}
public void stop()
{
if( isDriving )
{
isDriving = false;
}
else
{
}
}
}
Example 2: c# objects
using System;
class Book
{
public string title;
public string author;
public int pages;
}
class MainClass {
public static void Main (string[] args) {
Book book1 = new Book();
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.pages = 400;
Console.WriteLine(book1.title);
}
}
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;
}
}
class Program
{
static void Main()
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
Person person2 = person1;
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);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}