Skip to content

Instantly share code, notes, and snippets.

@technogeeky
Created July 21, 2014 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save technogeeky/637ed31fc2e03b26c475 to your computer and use it in GitHub Desktop.
Save technogeeky/637ed31fc2e03b26c475 to your computer and use it in GitHub Desktop.
non-zero-indexed arrays in C# ( csharp ) are not implictly castable.
static Func<int,int,Array> OffsetArray = (size,start) => Array.CreateInstance(typeof(string), new[] { size }, new[] { start });
static Func<int,int,string[]> OffsetArrayString = (size,start) => (string[]) Array.CreateInstance(typeof(string), new[] { size }, new[] { start });
public static void Main ()
{
Array a = OffsetArray(24,1990);
a.SetValue("I was born", 1990);
a.SetValue("I dislocated my shoulder", 1996);
a.SetValue("I was allowed to buy alcohol (big mistake)", 2008);
a.SetValue("I started a programming blog", 2013);
int lower = a.GetLowerBound(0);
int i = lower;
foreach(string s in a) {
string @event = s;
if (String.IsNullOrEmpty(@event)) @event = "i was a dull boy";
Console.WriteLine("In the year " + i++ + " of our lord: " + @event);
}
for (int year = a.GetLowerBound(0); year <= a.GetUpperBound(0); year++) {
string @event = (string) a.GetValue(year);
if (String.IsNullOrEmpty(@event)) @event = "i was a dull boy";
Console.WriteLine("In the year " + year + " of our lord: " + @event);
}
try {
string[] b = OffsetArrayString(24,1990);
} catch (InvalidCastException ice) {
Console.WriteLine("I can't do this because: \n\t" + ice.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment