negligible
negligible

Reputation: 350

C# multi casting example

Could someone write this literally for me so I can understand how the casting is being carried out? The amount of brackets confuses me.

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

Was only able to find simple cast examples searching (possibly means I'm searching for wrong thing) which weren't very helpful.

Upvotes: 5

Views: 1092

Answers (4)

robowahoo
robowahoo

Reputation: 1269

In order 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 is applied depends on MSDN's Operator precedence and associativity

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

Becomes

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

The cast operation is grouped into the "Unary Operators" category which is a lower priority than the indexer - [] which is in the "Primary expressions" category.

In the original line - The ()'s are necessary around the cast: ((Object[])e.Result) because the indexer - [] is applied immediately to the object on the left as the first priority. Without the surrounding ()'s the cast would be applied AFTER the indexer and since e.Result is (likely?) of type object this will fail at compile time. Without the ()'s the line would look like:

(Object[])e.Result[1] 

Which would not be valid.

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

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

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

Dictionary<String, String> cast2 = (Dictionary<String, String>) cast1[1];

Upvotes: 4

Jakub Konecki
Jakub Konecki

Reputation: 46008

Object[] cast1 = (Object[])e.Result;
Object secondElement = cast1 [1];
Dictionary<String, String> cast2 = (Dictionary<String, String>)secondElement;

Upvotes: 4

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

Firstly, e.Result is casted to an array of type Object

(Object[])e.Result

Then, the item at index 1 in that array, [1], is casted to a Dictionary of type <string, string>

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

Hope that helped.

Upvotes: 11

Roy Goode
Roy Goode

Reputation: 2990

object[] cast1result = (object[]) e.Result;
object dictionaryElement = cast1result[1];
Dictionary<string, string> cast2result = (Dictionary<string, string>) dictionaryElement;

Upvotes: 2

Related Questions