pink li
pink li

Reputation: 142

Is it possible to call method directly on object literals in C#?

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?

Upvotes: 0

Views: 673

Answers (4)

JK.
JK.

Reputation: 5136

Yes, and the best thing about it is that you don't even have to check for null.

Upvotes: 0

Senick
Senick

Reputation: 101

Yes it's valid. No problem with it.

Upvotes: 0

Schroedingers Cat
Schroedingers Cat

Reputation: 3139

Yes it is possible. However I would not recommend it in general, because it is confusing, and not clear to other developers what you are doing.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502825

Yes, it's absolutely valid and fine.

I suspect you don't always declare a variable even without using literals. For example, consider:

string x = "hello";
string y = x.Substring(2, 3).Trim();

Here we're using the result of Substring as the instance on which to call Trim. No separate variable is used.

But this could equally have been written:

string y = "hello".Substring(2, 3).Trim();

The same is true for primitive literals too:

string x = 12.ToString("0000");

Ultimately, a literal is just another kind of expression, which can be used as the target of calls to instance methods.

Upvotes: 11

Related Questions