|
-
August 10th, 2009, 04:02 PM
#9
Re: Generic class instance casting to generic class type
OK, this code compiles. WinForm with button and button click..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GenericTypesTest
{
class GenericClass<T> //Generic class.
{
public int AddValues<T>(int x, int y)
{
return x + y;
}
}
class UseClass //Class that uses the GenericClass
{
public int DoSomething(object o_classinstance)
{
if (o_classinstance.GetType() == typeof(GenericClass<int>))
{
GenericClass<int> o_localclassint = (GenericClass<int>)o_classinstance; //cast
return o_localclassint.AddValues<int>(1, 2);
}
else if (o_classinstance.GetType() == typeof(GenericClass<string>))
{
GenericClass<string> o_localclassstring = (GenericClass<string>)o_classinstance; //cast
return o_localclassstring.AddValues<string>(3, 4); // <- messy duplication..
}
else
return 0;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GenericClass<int> o_intclass = new GenericClass<int>();
GenericClass<string> o_stringclass = new GenericClass<string>();
UseClass o_useclass = new UseClass();
int z = o_useclass.DoSomething(o_intclass);
int i = o_useclass.DoSomething(o_stringclass);
MessageBox.Show(string.Format("Value Z: {0} Value y: {1}", z.ToString(), i.ToString()));
}
}
}
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
|