Reputation: 109
I'm (very) new to C#; I'm sure the solution here is simple but I can't figure it out.
Suppose I have a simple array of temperatures for Friday. I receive an abbreviation for the day and an hour (integer) from somewhere and I want to use it to print an element from the array:
using System;
public class Program
{
public static void Main()
{
double[] Friday = {54.5, 61.0, 63.5, 58.0};
string Today = "Fri";
int Hour = 1;
double parsed = Convert.ToDouble(Today + "day[" + int + "]");
Console.WriteLine(parsed);
}
}
Given these conditions, how do I output 61.0? Then end result should be equivalent to Console.WriteLine(Friday[1]);
Upvotes: 0
Views: 105
Reputation: 3754
If I really wanted to achieve that I would use a dictionary:
Dictionary<string, double[]> dayToValues =
new Dictionary<string, double[]>
{
{"Monday", new double[] {1.0, 2.0, 3.0} },
{"Friday", new double[] {4.0, 5.0, 6.0} }
};
string today = "Fri";
int hour = 0;
double firstHourValue = dayToValues[today + "day"][hour];
Console.WriteLine(firstHourValue); // prints "4"
If you really need to dynamically build the name of a variable and access it, you have to use reflection. Something like:
string fieldName = today.ToLower() + "day";
double[] todays = GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this) as double[];
Console.WriteLine(todays[1]); // prints "8"
This assumes that your have a private field in the current class:
double[] friday = { 7.0, 8.0, 9.0 };
Of course the reflection code depends on the exact location and scope of the variables. And obvioulsy you would need some null reference checks to use it in the real world. Anyway, using reflection looks quite irrelevant for what seem to be your needs. Use it only if you really have to.
Upvotes: 1
Reputation: 35477
c# uses zero-relative indexing. This means that the 1st element in the array has an index of zero. So you most likely mean Friday[0]
.
c# also has the ToString
method on all objects. This returns a "human readable" representation of the object. So you can do
Console.WriteLine(Friday[0].ToString());
Also, WriteLine
will auto-magically convert any object passed to it into its string repsentation. So this will also work
Console.WriteLine(Friday[0]);
If you want text and a value, then use a Format string, as in
Console.WriteLine("Friday {0}", Friday[0]);
See https://msdn.microsoft.com/en-us/library/system.string.format%28v=vs.110%29.aspx for more details on format strings.
Upvotes: 1