Question : C# 4.0 : Add a Constructor

You need to have automatic initialization of new objects of the class.

Answer : C# 4.0 : Add a Constructor

Define a special method, called a constructor, with the same name as the class, with no return type. A constructor runs when a type is created—it is never called directly.

Here are two constructors for the Vertex3d class—one taking arguments, the other performing some default initialization.

class Vertex3d
public Vertex3d()
_x = _y = _z = 0.0;

public Vertex3d(double x, double y, double z)
this._x =x;
this._y = y;
this._z = z;


Constructors do not need to be public. For example, you could make a protected constructor that is only accessible from derived classes. You could even make a private constructor that prevents instantiation (for utility classes) or is accessible only from other methods in the same class (static factory methods, perhaps).

Random Solutions  
programming4us programming4us