Created
March 11, 2022 14:33
-
-
Save michyprima/1df6a80aaaf7305efd1fd1cf19d10494 to your computer and use it in GitHub Desktop.
Getting an array element out of an object in c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.