Type Cast Operator Precedence
c#
Solution
Its quite simple really.
When you don't wrap the cast in brackets.. you're casting the entire expression:
return (Product)itemsList.Values[i].ProductName;
// |______________________________|
You're essentially casting a `string` to a `Product`. Whereas:
return ((Product)itemsList.Values[i]).ProductName;
// |____________________________|
Casts just that part, allowing the `.` to access the properties of a `Product`. Hopefully the bars help show you the difference more clearly.
Problem
I ran into a scenario today while implementing search functionality in my application that has left me puzzled. Check out this snippet: ``` public string GetFirstProductName(SortedList<string, object> itemsList) { for (int i = 0; i < itemsList.Values.Count; i++) { if (itemsList.Values[i] is Product) // Doesn't Compile: // return (Product)itemsList.Values[i].ProductName; // Does compile. Precedence for the "." higher than the cast? return ((Product)itemsList.Values[i]).ProductName; } } } ``` So, what is the precedence for the cast? Is a cast an operator? What about the `as` keyword - is that an operator and what is its precedence?