How to use string as variable name in c#

am having a viewstate which pertains value like:

string temp; ViewState["temp"] = dc.ColumnName.ToString();

This returns weekdays like: Monday,tuesday,wednesday etc

Now am using this value here:

string a = "txt" + ViewState["temp"].ToString();
TextBox a = new TextBox();

But it gives me error

Cannot implicitly convert type 'System.Web.UI.WebControls.Textbox' to 'string'

I want textbox variable name like txtmonday,txttuesday dynamically. Is there any way that I can assign variable name???

Jon Skeet
people
quotationmark

No, you can't. At least not without reflection, and you shouldn't be using reflection here. Variables in C# are a compile-time concept. (Even with reflection, it'll only work for fields, not for local variables.)

If you want a collection of values, use a collection... e.g. a List<T> or a Dictionary<TKey, TValue>. So for example, you could have a List<TextBox> (which is accessed by index) or a Dictionary<string, TextBox> which is accessed by string key ("monday", "tuesday" or whatever you want).

If you're only actually creating a single TextBox, what does it matter what the variable name is? Just use:

TextBox textBox = new TextBox();
// Do appropriate things with the TextBox, possibly using ViewState

The variable name just gives you a way of referring to the variable. That's all it's there for. The object you create doesn't know anything about which variables (if any) contain references to it.

people

See more on this question at Stackoverflow