Hello,
I would like one of my classes to behave like DataRow, when speaking about constructors. As far as I can remember, one cannot use the syntax DataRow myDataRow = new DataRow(), and can only obtain a new DataRow from a DataTable by calling the DataTable.NewRow() method. How can this be achieved in C#
To be more explicit, I have a class A, and another class AManager (which manages some stuff regarding A objects). I want to instantiate every A object with a syntax like
A test = new AManager.NewA(). And I don't want the user to be able to call A test = new A();
Thank you very much!
Andrei Ismail

Preventing a class from having a default constructor
Kiran Babu
You can do the following:
public class A
{
internal A()
{
}
}
public class AManager
{
public A NewA()
{
return new A();
}
}
This will allow this:
A test = AManager.NewA();
Only classes within your assembly (dll or executable) will be able to create a instance of A via its internal constructor. To prevent any class from creating A, except A itself, do the following:
public class A
{
private A()
{
}
public A NewA()
{
return new A();
}
}
You can then do the following:
A test = A.NewA();
HTH
David
Maruis Marais
First of all, thank you for your reply. I discovered the internal keyword in the meantime and I think it does its job quite nicely. However, I do miss friend from C++, where you were able to specify which classes from the same "assembly" can see the private members of your class. Do you know of a similar keyword in C# I think Microsoft used internal for its assemblies, but it's not necessarily good practice in my opinion. Friend was reputed to "break OOP", and internal is friend's bigger brother.
Best regards,
Andrei
Jim Fafrak
Unfortunately there is no equivalent keyword in C#.
However, you can have inner classes that are able to call private methods on their containing class:
public class A
{
private void MyMethod()
{
}
public class B
{
public B(A a)
{
a.MyMethod();
}
}
}