I'd like to know if there is some way to use the method of a casted object without creating a new variable. In other word, is there a way to do this:
abstract class event { }
class loop : event
{
public int a;
}
static void main ()
{
loop l = new loop();
l.a = 5;
event e = l; //supposing that
System.Console.WriteLine( (loop) (e).a );//error
loop lcast = (loop) e;
System.Console.WriteLine( lcast.a );//no error
}
Can I access the field a
without creating a temporary variable (lcast
)?
This is a problem with operator precedence. .
has a higher precedence than a cast, so this:
(loop) (e).a
is being treated as:
(loop) ((e).a)
You want to cast and then use the result in the member access - so you need to bind the cast more tightly than the .
for member access:
((loop) e).a
See MSDN for the full C# operator precedence rules.
See more on this question at Stackoverflow