Xander
Xander

Reputation: 31

Is it possible to dynamically name variables based off user input?

I've recently started working on a project in C# that requires the user to create as many instances of a class as they'd like. I've thought about two different ways to go about this.

1: Use a list of string arrays that contains the information held by the class. By this I mean when they create an instance of the class the data goes to a list so that I can re-use the same variable name.

// Initiating the class
dataSet1D currDataSet = new dataSet1D();
dataSet1D.name = txtName.Text;
dataSet1.length = Int32.Parse(txtIndex.Text);

// Creating the list of arrays
List<string[]> arrayList = new List<string[]>();
string[] strArray = new string[2];
strArray[0] = "name";
strArray[1] = "lengthAsString";
arrayList.Add(strArray);

(That was just some quick mock-up code, I'll obviously use better variable names on my actual project)

2: I could use dynamically named variables If they enter what they want as a name, I can name the instance that.

dataSet1D <dynamically named variable name> = new dataSet1D();

Upvotes: 0

Views: 1730

Answers (3)

Hasson
Hasson

Reputation: 1914

You can creat a dictionary which maps the name of the "variable" to the actual calss instance, or you can create a List which has all your instances and they have an index in this case rather than a name.

Upvotes: 2

Jay T
Jay T

Reputation: 863

You could create add a string property to the class which would hold the name the user specifies for each object. Then, as a new instance of each object is created, add it to a List as others have suggested. Finally when you need to access an instance by the user defined name, use a LINQ expression to retrieve it.

public class MyClass
{
    public string UserDefinedName { get; set; }
    public int Length { get; set; }
    ... Other member variables
}

public List<MyClass> UserCreatedObjects { get; set;}

Then to get an instance which was named, say "my_object_1" use LINQ:

var theInstance = UserCreatedObjects.Where(o => o.UserDefinedName == "my_object_1").FirstOrDefault();

Upvotes: 0

Ashkan S
Ashkan S

Reputation: 11501

If you need lots of instances of 1 class, you can just have a list of that class. Like this:

class MyClass
{
   public string Name {set;get;}
   // property2 , etc
}

var myList = new List<MyClass>();
myList.Add(new MyClass());

Other than this, I have to mention that variable names has nothing to do with the run-time. when you build your code, they will all change to pointers to space that contains the data.

Variable name is only a handler for programmers to let them work with their objects

Upvotes: 0

Related Questions