You don't actually need to do that. The compiler can do that for you if you
just overload a single "Set" method:
public void Set(TitleObject title) {
_title = title;
}
public void Set(DateObject date) {
_date = date;
}
// etc...
Because the method signatures differ, the compiler can figure out which one
you want at compile time based on the type you're passing in. Sadly, the
same trick doesn't work quite as cleanly for a "Get" function, because
return type is not part of a method's formal signature. The best you can do
on the flip side is to implement a generic "get" like this:
public object Get(string fieldname) {
switch(fieldname) {
case "title": return (object)_title;
case "date": return (object)_date;
default: return (object)null;
}
}
This works fine, but requires the caller to cast the result to the desired
type, which you can't necessarily trust them to do correctly.
--
Anything I post is solely my opinion, and is not necessarily representative
of my employer's positons.
My answers are not always correct, but I do my best to be accurate and
helpful.
"Pekka Henttonen" <no********@kolumbus.fi> wrote in message
news:MP************************@news.kolumbus.fi.. .
Let's say there is an object which has several methods all taking
different object as argument:
class TestObject {
public void SetTitle( TitleObject title );
public void SetDate( DateObject date );
<etc.>
}
How can you find out which method to call at runtime when you have an
object which should be passed to a method? I suppose there is a cleaner
way to do it than by testing all possibilities by a set of if-clauses:
public void SetNull( Object o ) {
if ( o is TitleObject ) {
SetTitle(null);
} else
if ( o is DateObject ) {
SetDate(null);
} else
<etc.>
}
With best regards
Pekka
Kerava, Finland