How do I create a 2d array in my class that stores names and prices as strings? And how do I make it accessible from my form without using an object? So far I have the following in my class.
class Name
{
public string SpecialCakeName()
{
string[,] strSpecialCakeName = new string[4, 2];
strSpecialCakeName[0, 0] = " ";
strSpecialCakeName[0, 1] = " ";
strSpecialCakeName[1, 0] = " ";
strSpecialCakeName[1, 1] = " ";
strSpecialCakeName[2, 0] = " ";
strSpecialCakeName[2, 1] = " ";
strSpecialCakeName[3, 0] = " ";
strSpecialCakeName[3, 1] = " ";
return strSpecialCakeName[0,0];
}
}
However, I don't know that this is even the right approach. Also how would I be able to access this array without using something like 'Name cakeName = new Name();'in my form?
I suggest a Dictionary object. Using strings to store price information is a bad idea. A Dictionary<string,decimal> will allow you map a string cake name to a decimal price without needing to define a whole custom object (though, really, that may be what you need here).
To access the dictionary without needing an instance of your class, build it like this:
public class Names
{
private static Dictionary<string, decimal> _specialCakes = new Dictionary<string,decimal>{
{"Cake 1", 1.00m},
{"Cake 2", 2.50m},
{"Cake 3", 4.00m}
};
public static Dictionary<string, decimal> SpecialCakes {
get {return _specialCakes;}
}
}
Now you can look up a price like this:
decimal Cake1Price = Names.SpecialCakes["Cake 1"];
Or loop through a list of all cake names like this:
foreach(string name in Names.SpecialCakes.Keys)
{
//and within the loop reference a price for that cake like this:
decimal currentPrice = Names.SpecialCakes[name];
}
Make it static:
public static string SpecialCakeName()
{
...
}
then you can call it using class type:
string[,] names = Name.SpecialCakeName();
Use Dictionary instead.
Dictionary<string, decimal> strSpecialCakeName = new Dictionary<string, decimal>();
strSpecialCakeName.Add({"somename", 100/*some decimal price*/});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.