A class is a custom type consisting of field data (member variables) and members (attributes, methods, constructors, events, and so on) operating field data. Field data indicates the status of the class instance (object.
In C #, classes are defined using the class keyword, for example:
Public ClassCar
{
//Car field (Status)
Private Int_ Speed;
Private String_ Name;
//Attribute of the Car operation field
Public IntSpeed
{
Set{This. _ Speed=Value ;}
Get{Return This. _ Speed ;}
}
Public StringName
{
Set{This. _ Name=Value ;}
Get{Return This. _ Name ;}
}
//Explicitly define the default constructor
PublicCar (){}
//Custom Constructor
PublicCar (StringName,IntSpeed)
{
This. _ Name=Name;
This. _ Speed=Speed;
}
//Car functions (methods)
Public VoidShowState ()
{Console. WriteLine ("Car {0} is going {1} MPH",This. _ Name,This. _ Speed );}
}
In addition, fields of the class are rarely defined as public. To protect the integrity of state data, it is best to define the field data as private (or protected ), and then provide externally controlled access through properties.
UseNewKeyword to allocate objects
The object must be allocated to the memory using the new keyword. If the new keyword is not used, and then the class variable is used, a compilation error is returned.
Public Static VoidMain (String[] Args)
{
//Error. Forgot to use new
Car c;
C. Name="Bruce";
}
Correct example:
Public Static VoidMain (String[] Args)
{
//Create a Car object.
Car c;//Declares a reference to a Car object that has not been created.
C=NewCar ("Bruce wong",150);//Assign a valid reference to the object through new, which directs to the effective object in the memory.
C. ShowState ();
Console. ReadKey (True);
}
Bytes
Class Constructor
Purpose: assign a value to the field (State) of the object, which allows you to create its state when creating the object.
Constructor is a special type of method that is called indirectly when an object is created using the new keyword.
Note: The constructor does not return values (even void). Its name is always the same as the class name.
Default constructor
C # provides a default constructor, which can be redefined if needed. The default constructor does not accept any parameters. It allocates new objects to the memory and ensures that all fields are set to the correct default value. If you are not satisfied with these default values, you can redefine the default constructor. For example:
public Car()
{
this._name="My Car