C # multiple cast example

Can someone write this literally for me so that I can understand how casting is done? The number of brackets confuses me.

(Dictionary<String, String>)((Object[])e.Result)[1];

Only the search for simple examples of drives was available (perhaps this means that I was looking for the wrong thing), which were not very useful.

+4
source share
4 answers

First, e.Result is passed to an array of type Object

 (Object[])e.Result 

Then the element at index 1 in this array [1] is passed to a dictionary of type <string, string>

 (Dictionary<String, String>)((Object[])e.Result)[1]; 

Hope this helps.

+10
source

To understand the order of operations, you need to remember that the cast will be applied to the object to the right, but the rules that affect WHEN it depends on MSDN The priority of operators and associativity

 (Dictionary<String, String>)((Object[])e.Result)[1]; 

becomes

 Object[] cast1 = (Object[]) e.Result; 

The casting operation is grouped into the category “Unary operators”, which is a lower priority than the index - [], which is located in the category “Primary expressions”.

In the original line, - () is needed around cast: ((Object []) e.Result), because indexer - [] is applied immediately to the object on the left as the first priority. Without the surrounding () cast, it will be applied AFTER the indexer, and since the e.Result (probably?) Is an Object of type, this will happen at compile time. Without () the line will look like this:

 (Object[])e.Result[1] 

Which is invalid.

 ((Object[])e.Result)[1] 

ensures that e.Result will distinguish first the type Object [], and then the indexer is used to access the first element.

The second cast turns the first casted object [] element (in my example cast 1) into a dictionary

 Dictionary<String, String> cast2 = (Dictionary<String, String>) cast1[1]; 
+4
source
 Object[] cast1 = (Object[])e.Result; Object secondElement = cast1 [1]; Dictionary<String, String> cast2 = (Dictionary<String, String>)secondElement; 
+4
source
 object[] cast1result = (object[]) e.Result; object dictionaryElement = cast1result[1]; Dictionary<string, string> cast2result = (Dictionary<string, string>) dictionaryElement; 
+2
source

Source: https://habr.com/ru/post/1395766/


All Articles