-
August 10th, 2009, 10:30 AM
#1
Generic class instance casting to generic class type
Hi,
I am a newbie to c# and have the following problem to do with generic type casting to use 'generically' see '***' below
Probably best to explain this one with some simple code..
...
class GenericClass<T> //Generic class.
{
public AddValues<T> (int x, int y) : int
{
return x + y;
}
}
class UseClass //Class that uses the GenericClass
{
public DoSomething(object o_classinstance) : int
{
... *** The code below works, but is not neat. How can I eliminate the duplication?
if (o_classinstance.GetType() == typeof(GenericClass<int>))
{
GenericClass<int> o_localclassint = (GenericClass<int>)o_classinstance; //cast
return o_localclassint.AddValues(1, 2);
}
else if (o_classinstance.GetType() == typeof(GenericClass<string>))
{
GenericClass<string> o_localclassstring = GenericClass<string>)o_classinstance; //cast
return o_localclassint.AddValues(3, 4); // <- messy duplication..
}
}
}
....
... in program ...
....
{
..
GenericClass<int> o_intclass = new GenericClass<int>();
GenericClass<string> o_stringclass = new GenericClass<string>();
o_useclass = new UseClass();
int z = o_useclass.DoSomething(o_intclass);
int i = o_useclass.DoSomething(o_stringclass);
..
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|