Skip to content

Instantly share code, notes, and snippets.

@michyprima
Created March 11, 2022 14:33
Show Gist options
  • Save michyprima/1df6a80aaaf7305efd1fd1cf19d10494 to your computer and use it in GitHub Desktop.
Save michyprima/1df6a80aaaf7305efd1fd1cf19d10494 to your computer and use it in GitHub Desktop.
Getting an array element out of an object in c#
//I didn't know you could do this, figured it out from the docs
//I had to get a specific element out of an array which was returned from a library as a single object and didn't want to cast to the specific type
//An example:
object test = new int[] { 1, 2, 3, 4, 5 };
//ideally you would do this
object test2 = ((int[])test)[1]; //but this means you need to account for each type test can be
//this does not work (throws)
object test2 = ((object[])test)[1];
//this does - test2 is 2
object test2 = ((Array)test).GetValue(1);
@michyprima
Copy link
Author

michyprima commented Mar 11, 2022

Also declaring test as dynamic is another way to get around this problem, but I prefer to leave dynamic as a last resort, especially when you need to take performance into account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment