HI, i will be very shocked if this is possible but i have a lot of variables all with “Defaults” at the end and i want to store all of them into an array using strings to change the variable referenced in a for loop each cycle, thanks in advance.
What you’re describing is how you might do something in a dynamically typed language such as Python or JavaScript, but not in a strongly typed language like C#.
To do something similar you need to learn how to use Dictionaries in C#. Python and JavaScript objects are basically just Dictionaries in disguise.
Here’s a small tutorial on dicitonaries: C# Dictionary
You can but be aware that the value types (ie ints, floats, structs, etc) are boxed when converted to object
which comes with a performance penalty and allocates memory. Additionally the approach below requires you to either come up with a way to track what type is being stored or remember what you’ve stored it as when you read it.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing
var dictionary = new Dictionary<string, object>();
dictionary.Add("x", 5);
dictionary.Add("y", 3.14);
dictionary.Add("z", new List<int>());
For example (written by GPT-4o).
var dictionary = new Dictionary<string, (Type, object)>();
dictionary.Add("x", (typeof(int), 5));
dictionary.Add("y", (typeof(double), 3.14));
dictionary.Add("z", (typeof(List<int>), new List<int>()));
// Checking the type
void CheckTypeAndPrint(string key)
{
if (dictionary.TryGetValue(key, out var valueTuple))
{
Type type = valueTuple.Item1;
object value = valueTuple.Item2;
if (type == typeof(int))
{
int intValue = (int)value;
Console.WriteLine($"Key: {key}, Type: int, Value: {intValue}");
}
else if (type == typeof(double))
{
double doubleValue = (double)value;
Console.WriteLine($"Key: {key}, Type: double, Value: {doubleValue}");
}
else if (type == typeof(List<int>))
{
var listValue = (List<int>)value;
Console.WriteLine($"Key: {key}, Type: List<int>, Value: {listValue}");
}
else
{
Console.WriteLine($"Key: {key}, Type: {type}, Value: {value}");
}
}
else
{
Console.WriteLine($"Key: {key} not found in the dictionary.");
}
}
// Example usage
CheckTypeAndPrint("x");
CheckTypeAndPrint("y");
CheckTypeAndPrint("z");
I read the replies but it seems to me that this is not what you are asking. Maybe an example (examples are generally a good idea). From the sounds of it my answer will be “don’t do that”
Thanks so much!
Thanks but i need to use it in other classes
oh i just knew how