A class is a group of related methods and variables. A class describes these things, and in most cases, you create an instance of this class, now referred to as an object. On this object, you use the defined methods and variables. Of course, you can create as many instances of your class as you want to.
When you define a class, you define a blueprint for a data type. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class.
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces.
Example of a Class is given below:
class Bike
{
private string color;
public Bike (string color)
{
this.color = color;
}
public string Show()
{
return "This bike is " + Color;
}
public string Color
{
get { return color; }
set { color = value; }
}
}
Above code we have defined a new class, called Bike.. It defines a single variable, called color, which of course is used to tell the color of bike. We declared it as private, which is good practice - accessing variables from the outside should be done using a property. The Color property is defined in the end of the class, giving access to the color variable.
Besides that, our Bike class defines a constructor. It takes a parameter which allows us to initialize Bike objects with a color. Since there is only one constructor, Bike objects can only be instantiated with a color. The Show() method allows us to get a nice message with the single piece of information that we record about bike color. It simply returns a string with the information we provide.
Note:
1. Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private.
2. Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any.
3. To access the class members, you use the dot (.) operator.
4. The dot operator links the name of an object with the name of a member.