Reputation: 7397
According to the C# grammar, one can write
(A)(B)
which can be interpreted either as an invocation expression or a type cast. Can someone please provide a valid C# example that interprets this case as an invocation expression?
This is the grammar rule I'm referring to:
invocation-expression:
primary-expression ( argument-list? )
and primariy-expression
can be a parenthesised expression.
Upvotes: 2
Views: 95
Reputation: 5415
It seems Visual Studio complains about this: (TestMethod)();
But this is evaluated as a function call (assuming TestMethod is a method): (this.TestMethod)();
Unless TestMethod is static, in which case even (MyClass.TestMethod)();
doesn't work.
I think it's because something like this.TestMethod
unambiguously evaluates to a method group. There is no scenario where this.anything
would evaluate to a type. But classname.something
could be a nested type, or it could be a static method, so VS seems to interpret that as a type.
Upvotes: 1
Reputation: 13217
Like this?
((Action<string>)Console.WriteLine)("test");
Or this, as an expression:
((Func<int>)Console.Read)()
Edit: I doubt there is a way for primary-expression
to be a simple identifier, as this always gets parsed as a cast (even (writeLine)()
), but it's not a big deal, as you can always just remove the parentheses.
Upvotes: 4