tags:

views:

79

answers:

2

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?

+2  A: 

Constructor chaining works like that :

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;
}
madgnome
But what if the table doesn't contain any data? It will throw an exception which I can't catch.
ApoY2k
@ApoY2K - You can catch the exception when constructing the `TestObject` object.
Oded
gehho
+6  A: 

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.

Oded