Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Constructor parameter passing

Tags:

c#

constructor

I currently restruct my program to be more object-orientated and I'm having trouble with the constructors of my objects.

All objects are stored in a database which has to be human-readable, so I figured it would be nice for the programmer to pass the constructor of an object the table or datarow directly and the object would get the values itself.

So, what I wanted to do was this:

public TestObject(Data.MyDataTable table) {
 // Some checks if the table is valid
 TestObject(table[0]);
}

public TestObject(Data.MyDataRow row) {
 // Some checks if the row is valid
 TestObject(row.Name, row.Value);
}

public TestObject(String name, String value) {
 // Some checks if the strings are valid
 _name = name;
 _value = value;
}

So, as you see, I want sort of a "constructor chain" that, depending on how the programmer calls it, the values are passed through and validated in each step. I tried it the way I wrote it, but it didn't work.

Error 'TestObject' is a 'type' but is used like a 'variable'

I also tried writing this.TestObject(...) but no changes.

Error 'TestObject' does not contain a definition for 'TestObject' and
no extension method 'TestObject' accepting a first argument of type
'TestObject' could be found

How can I go about this?

like image 401
F.P Avatar asked Apr 10 '26 12:04

F.P


1 Answers

You chain constructors like this:

public TestObject(Data.MyDataTable table) : this(table[0])
{

}

public TestObject(Data.MyDataRow row) : this(row.Name, row.Value)
{

}

public TestObject(String name, String value) 
{
 // Some checks if the strings are valid
 _name = name;
 _value = value;
}

Note: the use of the this keyword to indicate the current object, use of the parameters that are passed in to one constructor to the chained constructor.

like image 58
Oded Avatar answered Apr 12 '26 03:04

Oded