O
O.o
I have a method that should accept an input argument of one of several
types (or classes). One way of doing this is to overload the method.
That's fine, but what I've realized is that every version of the
method is identical (except for the type or class of input argument).
This is because the different input types or classes are already
handled by overloaded operators (when necessary). My question then is:
do I really need to copy and paste the exact same code for each type
or class of input argument?
A simple example might be a method called "Add", that takes two
numbers as input and returns a double value representing their sum:
public static double Add( int arg1, int arg2 )
{
return (double)(arg1+arg2);
}
public static double Add( float arg1, float arg2 )
{
return (double)(arg1+arg2);
}
and so on for short, long, decimal, etc..., not to mention any other
types or classes that have an overloaded "+" operator that returns a
double.
OK, so my method is a bit more complicated, but it seems to me that
there ought to be a way for a method to accept arguments from a list
of types. I don't want to use the Object "type", because then I have
to add a bunch of code to check and see if it contains a "legal" type.
I also don't want to re-cast the input data to another type and call a
"default" method, which would increase computational cost and memory
for "small" input types. Is there another way?
types (or classes). One way of doing this is to overload the method.
That's fine, but what I've realized is that every version of the
method is identical (except for the type or class of input argument).
This is because the different input types or classes are already
handled by overloaded operators (when necessary). My question then is:
do I really need to copy and paste the exact same code for each type
or class of input argument?
A simple example might be a method called "Add", that takes two
numbers as input and returns a double value representing their sum:
public static double Add( int arg1, int arg2 )
{
return (double)(arg1+arg2);
}
public static double Add( float arg1, float arg2 )
{
return (double)(arg1+arg2);
}
and so on for short, long, decimal, etc..., not to mention any other
types or classes that have an overloaded "+" operator that returns a
double.
OK, so my method is a bit more complicated, but it seems to me that
there ought to be a way for a method to accept arguments from a list
of types. I don't want to use the Object "type", because then I have
to add a bunch of code to check and see if it contains a "legal" type.
I also don't want to re-cast the input data to another type and call a
"default" method, which would increase computational cost and memory
for "small" input types. Is there another way?