Hi in Actionscript I may refer to a variable within an object thusly
objectName["variableName"] = "Some value";
How would I do the equivalent in c#
thanks
Hi in Actionscript I may refer to a variable within an object thusly
objectName["variableName"] = "Some value";
How would I do the equivalent in c#
thanks
Dictionary is not part of the language & is provided in the framework.
Use Dictionary<Key, Value>.
e.g.
Dictionary<string, string> myData = new Dictionary<string, string>();
myData.Add("first", "stack");
myData.Add("second", "overflow");
Console.WriteLine(myData["first"]);
You could use a dictionary...
using System.Collections.Generic;
public class x{
public method1() {
var objectName = new Dictionary<string, object>();
objectName["variableName"] = "Some value";
}
}
Or, use strongly-typed properties (safer and fast running), recommended where you know variable names at compile-time.
public class Person{
public string Name {get;set;}
public int Age {get;set;}
}
// and use it as follows in your functions
var person1 = new Person() {
Name = "Fred",
Age = 21,
};
// again, to demonstrate different syntax to do same thing
var person2 = new Person();
person2.Name = "Danny";
person2.Age = 2;
person2.Age = "x"; // won't compile - expects int, hence safer
C# doesn't have "objects with variables". C# objects have properties which are accessed like MyObject.PropertyName.
What you're referring to is a key-value collection. A Dictionary is C# implementation of this. Note that a dictionary only allows for unique keys. You can use it generically so you can use it like this.
Dictionary<string, string> myValues = new Dictionary<string, string>();
myValues.Add("variableName", "variableValue");
or
Dictionary<string, int> familySizes = new Dictionary<string, int>();
familySizes.Add("simpsons", 5);
As you can see you can choose what datatypes you use.