Paul Albers
Paul Albers

Reputation: 186

Create variable dynamically from textbox

I am trying to create some variables dynamically from a textbox or xml-script. So far I am making a program to create scripts for the server application. In that script I want to use variables which you can create in a form by entering a name and the type and maybe the scope.

So, if I enter Counter as an Int it has to create a variable called Counter. Like: int Counter = 0;

Upvotes: 0

Views: 985

Answers (3)

abhilash
abhilash

Reputation: 5651

Dictionary<String,Type> dynamicVars = new Dictionary<String,Type>();

dynamicVars.Add("Counter",typeof(int));

The above code segment would do it. But I cannot fathom why you would need such a thing ?

Just Curious...

Upvotes: 0

Mike Webb
Mike Webb

Reputation: 9003

Simple way would be to use a dictionary:

Dictionary<string, object> dynamicVars = new Dictionary<string, object>();

You might have to wrap that in a class and add type checking for the objects in the dictionary, but the dictionary will give you the ability to create and add any type of name/value pair.

Upvotes: 2

vcsjones
vcsjones

Reputation: 141638

Creating a variable based on input isn't a good idea, it's a huge amount of work and required a dynamic runtime. A much more simple approach is to use a Dictionary<TKey,TValue>, and use the text in the TextBox as a key.

Upvotes: 0

Related Questions