Reputation: 2667
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?
Upvotes: 3
Views: 1891
Reputation: 21108
It is not about precedence. Always value is converted
// Does compile. Precedence for the "." higher than the cast?
return ((Product)itemsList.Values[i]).ProductName;
in your case value is being returned by itemsList.Values[i]
which is being casted into Product. Then you are trying to access ProductName from it.
CAST is an Operator
Is/as
works only on reference types
return (itemsList.Values[i] as Product).ProductName;
READ MORE to understand difference between CAST and AS
Upvotes: 1
Reputation: 144206
x.y
has a higher precedence than the cast:
7.3.1 Operator precedence and associativity
The following table summarizes all operators in order of precedence from highest to lowest:
Primary x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
Unary + - ! ~ ++x --x (T)x
Upvotes: 4
Reputation: 4860
(Product)itemsList.Values[i].ProductName;
means (Product)(itemsList.Values[i].ProductName);
whereas second line you explicitly say to cast Values[i]
and then do .ProductName
;
Upvotes: 1
Reputation: 65077
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.
Upvotes: 14