Wednesday, April 29, 2009

Convert a delimited string to an interger array


public static int[] ToIntArray(this string value, char separator)
{
return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
}

So we can do something like this:

int[] result = "1,2,3".ToIntArray(',');

Convert an Enum Array into an Interger Array


DayOfWeek[] enumArray = new DayOfWeek[] {
DayOfWeek.Monday, DayOfWeek.Wednesday };

//Convert enum to int array
int[] result = Array.ConvertAll<DayOfWeek, int>(enumArray,
delegate(DayOfWeek value) { return (int)value; });

//with C# 3.0, a lambda:
int[] result2 = Array.ConvertAll(enumArray, value => (int) value);

//with C# 3.0 using Cast
int[] result3 = enumArray.Cast<int>().ToArray();

Tuesday, April 28, 2009

Measure a function's performance

Use the Stopwatch (in System.Diagnostics)

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms",
sw.Elapsed.TotalMilliseconds);

Tuesday, April 21, 2009

C# - Run a Process (Run an EXE)

CodeProject: Windows Services Can Install Themselves. :

Process myProcess = new Process();
string path = @'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727';
myProcess.StartInfo.FileName = path + '\\InstallUtil.exe';
myProcess.StartInfo.Arguments = @'/u C:\Service1\Service1.exe';
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();

myProcess.WaitForExit(60000);
if (!myProcess.HasExited)
myProcess.Kill();
myProcess.Close();