Generally in C# classes are Initialized as shown below.
Class_name cs= new Class_name();
But in some cases like it is done differently. Can anyone brief about it.
Example :
DataTable custTable = new DataTable(); // Class DataTable Initialization
DataRow row1 = custTable.NewRow();
The way DataRow class Initialized is different can any one explain this kind.
CodePudding user response:
Classes are always initialized with the new
keyword and a constructor.
MyClass x = new MyClass();
MyClass y = new MyClass(1,2,3);
MyClass z = new MyClass(x);
Now it is possible the initialization is inside a method of another class, or a static method of your class. Regardless, the new
keyword is still used inside the class.
There is nothing stopping you from creating code like this in order to control who can call the constructor.
public class MyClass
{
private Class() { }
static MyClass Create()
{
return new MyClass();
}
}
MyClass x = MyClass.Create();
With the above code the only way a consumer of MyClass
can create an instance is through the Create()
method.
A similar pattern is common where a class is initialized from another class
public class Simulation
{
public Results Calculate(Conditions cond)
{
return new Results(this, cond);
}
}
public class Results
{
public Result(Simulation sim, Conditions cond)
{
}
}
Simulation sim = new Simulation();
Conditions cond = new Conditions();
Results r = sim.Calculate(cond);
CodePudding user response:
Easier example, using string
string a = "first"; // from literal
string b = MakeMessage(); // from method
string c = new string("third"); // from constructor
string MakeMessage()
{
return new string("second");
}
Even though string are immutable, this is essentially the same thing (other than the literal).
A constructor (new string()
) is a method. All you're doing is executing a method and saving the result to a variable.
Sometimes authors of an API will choose not to allow the constructor to be public, and thus the only way to construct an object is with static methods or a method from a "parent" object.
CodePudding user response:
That's because custTable.NewRow()
is a simply way to create and add a new DataRow to your table ('custTable'), being this DataRow equals to all other DataTable rows (same colums f.e. I mean). You cannot create new DataRow()
because you need to have this DataRow associated to a DataTable scheme, in order to have all DataRows in same DataTable with same properties (columns, f.e.).
Hope this was clear!