I’m trying to create a List<T> where the user specifies what the data type is by selecting it from a ComboBox on the UI. I’ve managed to create an object of the CustomEntity, which holds the List<T>, but once I exit from the Button1_Click event handler, the CustomEntity will go out of scope. Is it possible to create a class level variable? I tried but had to comment it out as it caused an error.
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 CustomClassWithGenericList
{
public partial class Form1 : Form
{
//The following error is created: Cannot implicitly convert type
//CustomClassWithGenericList.CustomEntity<decimal> to
//CustomClassWithGenericList.CustomEntity<object>
//private CustomEntity<object> input1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (cb1.SelectedItem.ToString().ToUpper() == "DECIMAL")
{
input1 = new CustomEntity<decimal>();
string[] temp = textBox1.Text.Split(',');
foreach (string s in temp)
{
decimal number;
if (decimal.TryParse(s, out number))
{
input1.inputValue.Add(number);
}
else
{
MessageBox.Show("Error occured.");
}
}
}
else if(cb1.SelectedItem.ToString().ToUpper() == "INT")
{
}
else if(cb1.SelectedItem.ToString().ToUpper() == "TIMESPAN")
{
}
}
}
public class CustomEntity<T>
{
public List<T> inputValue;
public CustomEntity()
{
inputValue = new List<T>();
}
}
}
There are plenty of techniques could be used there. First of all you could create
Objector dynamic type variable and just casting it any you want.Also you could store your data in some state in memory (like some session or application state, or cache, stuff like that) and in such case just take it from this source.