Tutorial 10: Classes & Objects
As you know C# is an Object Oriented Programming Language, so things are associated with classes and objects with attributes and methods included. For example a Keyboard's attributes include Type, Color etc and methods include KeyPress, KeyUp, KeyDown etc. When you define a class you are actually defining what your data will be and what type of methods you can perform on that specific data type. Objects are instances of a class. When a class is declared, there is no memory assigned to objects. Memory is assigned as soon as object of a class is created.
Declaring Classes
A class is declared using class keyword in C#. The general syntax for creating a class can be as follow:
//Access modifier - class - class identifier
public class Vehicle
{
// Properties,
Fields,
Methods and Events
}
where
Vehicle is class name.
Adding fields to a Class
Variables which are declared and used in a class are referred as fields. These fields can be of any
data types available in C#. If you specify no access modifier before field it will be internal.
We will discuss access modifier in next tutorial. Below is an example how can you add fields
to a class.
public class Vehicle
{
int no_of_wheels;
string color;
int engine_no;
}
In above example, there are three fields, two of integer type and one of string type.
Adding methods to a Class
You can also add methods to a class. Methods in class defines how an object/instance of class will behave.
public class Vehicle
{
int no_of_wheels;
string color;
int engine_no;
public void VehicleInfo()
{
Console.WriteLine("Color of Vehicle is"+color);
Console.WriteLine("No of Wheels, in vehicle are "+no_of_wheels);
Console.WriteLine("Engine No. of Vehicle is"+engine_no);
}
}
Creating an Object
A class and objects are two different things. A Class is actually defining an object whereas an object is an instance of a class. When you create an instance reference of class is returned to the used for example in example below v1 holds the reference of Vehicle instance. You can create an object by using new keyword:
Vehicle
v1 = new
Vehicle
();
Accessing Class Members
You can access members of a class using . (dot) operator.
Vehicle
v1 = new
Vehicle
();
Console.WriteLin(v1.color);
v1.VehicleInfo();
Here is complete example of above code.
Output of above code will be:
Vehicle Color is: Blue
Engine No is: 1234
No. of wheels in Vehicle are: 4
In next tutorial we will discuss access modifiers.