Reputation: 4915
I have a string array in C# 3.5:
string [] times = new[] {“08:00 am” , “10:00 am”, “120”} ;
I would like to create indexes to times: StartTime
, EndTime
, ElapsedTime
so that when I code:
StartTime= “09:00 am” ;
EndTime= “11:00 am” ;
then times[0]
is set to “09:00 am”
, etc.
I could create 3 methods:
private void StartTime(string time)
{ times[0] = time; }
private void EndTime(string time)
{ times[1] = time; }
private void ElapsedTime(string time)
{ times[2] = time; }
and code
StartTime("09:00");
but is there a simpler way to do it?
Upvotes: 1
Views: 746
Reputation: 138874
What you should really do is create a new class to do this. Make the two times properties.
And the time elapsed is a function of the start and end times.
class Time
{
public DateTime StartTime{ get; set; }
public DateTime EndTime{ get; set; }
public String[] ToStringArray()
{
String[] ret = new String[3];
ret[0] = StartTime.ToString();
ret[1] = EndTime.ToString();
ret[2] = ElapsedTime().ToString();
return ret;
}
public TimeSpan ElapsedTime()
{
return EndTime.subtract(StartTime);
}
}
Upvotes: 20
Reputation: 16065
To add to jjnguy's answer, you should really have a class that holds the 3 properties, and then if you need an array you could have a public property that just has a getter and returns the 3 different times in a string array.
Upvotes: 2
Reputation: 147224
You can do this using a dictionary.
e.g.
Dictionary<string, string> times = new Dictionary<string, string>();
times.Add("StartTime","09:00am");
times.Add("EndTime","11:00am");
Upvotes: 0
Reputation: 6859
How about an extension method?
public static class Extensions
{
public static void StartTime(this string[] array, string value)
{
array[0] = value;
}
}
Upvotes: 0
Reputation: 158309
I don't know it it is simpler, but I would suggest taking the hard index references out of your code and replace them with constants, to make easier to maintain if the order of elements in the array would change in the future:
private const int START_TIME = 0;
private const int END_TIME = 1;
private const int ELAPSED_TIME = 2;
Then you will also get more readable code:
times[END_TIME] = time;
Unless you want to be more object oriented, in which case you should follow jjnguy's advice.
Upvotes: 3