Overloading
Instance Constructor
A class can have multiple instance constructors that can be overloaded
In C# we can supply parameters to constructors.
Having more than one constructor allows you to create the object with different parameters.
You must make sure each constructor has a unique signature.
The signature is composed of its name and its parameter list.
public class MyClass
{
public MyClass()
{
}
public MyClass(string str)
{
}
}
Private Constructor
This is often used in classes that only contain static members.
When a class has one or more private constructors and no public constructors, other classes cannot create instances of this class.
public class MyClass
{
private MyClass()
{
}
}
Static Constructor
A static constructor can be used to initialize any static data (or perform actions that only need to be done once).
public class MyClass
{
static readonly string _initialize;
static MyClass ()
{
this._initialize; = "only once";
}
}
Copy Constructor
A copy constructor is not provided by default but you can easily add one.
public class MyClass
{
private string _internal;
public MyClass (MyClass previousClass)
{
this._interna1 = previousClass._internal;
}
}
Copy Constructor calling Instance Constructor
A copy constructor is not provided by default but you can easily add one.
public class MyClass
{
private string _internal;
public MyClass(string param1)
{
this._internal1 = param1;
}
public MyClass (MyClass previousClass): this(previousClass._internal)
{
}
}
Calling A Different Constructor
It is possible for one constructor to invoke another constructor in the same object using the "this" keyword.
Lets imagine that we have 3 ways to create an object.
The first way is to pass in 1 parameters.
The second way is to pass in 2 parameters
The third way is to pass in 3 parameters.
public class MyClass
{
private string _internal1;
private string _internal2;
private string _internal3;
public MyClass(string param1)
{
this._internal1 = param1;
}
public MyClass(string param1, string param2)
: this(param1)
{
this._internal2 = param2;
}
public MyClass(string param1, string param2, string param3)
: this(param1, param2)
{
this._internal3 = param3;
}
}
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext