Project2051
Project2051

Reputation: 3

Using method on previous method's return value, C#

For example, I understand that I am able to do this:

string x = Int32.Parse("123").ToString();

Instead of:

int y = Int32.Parse("123");
string x = y.ToString();

because Parse() method returns and integer and then I can use ToString() method on an integer. But what is this technique called? I couldn't put it into words to google for more information. Is it yummies of .NET/high-level programming, or are you able to do this in low-level programming languages too, like C?

Upvotes: 0

Views: 457

Answers (5)

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3229

Yep.. As every one said, this is a method chaining. and this exists even in jQuery if you have noticed.

$('#id').show(300).html('XYZ').hide(500);

Upvotes: 0

Gerald Versluis
Gerald Versluis

Reputation: 33993

It's called "Method chaining" get that into Google and you should get some helpful results!

Upvotes: 1

spender
spender

Reputation: 120400

It's method chaining, which taken to more of an extreme can be used to create fluent interfaces. This is the basis of (method chain stated) LINQ.

As this gives a larger surface area in which exceptions can occur, it's not recommended if you need to check your assumptions along the way (checking for nulls, etc).

Upvotes: 1

Habib
Habib

Reputation: 223227

That is called Method chaining. Here is the details:

Universal method chaining 

You may want to see this article with respect to LINQ

Understanding LINQ to Objects (2) Method Chaining

Example from the Article:

int[] source = new int[] { 0, 1, -2, 3, 24, 6, 3 };
var results = source.Where(item => item > 0 && item < 10)
                    .OrderBy(item => item)
                    .Select(item => item.ToString(CultureInfo.InvariantCulture))

Upvotes: 2

Kinexus
Kinexus

Reputation: 12904

It's known as method chaining. See here for a little more information: Method chaining

I think an important point to be taken from the above wiki is;

Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a Fluent Interface.

Upvotes: 4

Related Questions