In C#, when calling some instance methods, We always declare a variable of that type, then assign a value to it, and call that method at last:
string str = "this is a string";
int test = str.IndexOf("a");
In Javascript, we can do this:
var test = 'sdfsldkfjskdf'.indexOf('a');
Is this kind of method calls legal in C#, say, directly use the string literal as a shorthand, without the declaration of a variable?
Yes, it’s absolutely valid and fine.
I suspect you don’t always declare a variable even without using literals. For example, consider:
Here we’re using the result of
Substringas the instance on which to callTrim. No separate variable is used.But this could equally have been written:
The same is true for primitive literals too:
Ultimately, a literal is just another kind of expression, which can be used as the target of calls to instance methods.