Reputation: 4303
As I am new to C# ,just wish to know, can i perform function chaining in C# like jQuery ?
Example jQuery :
$("#gview tbody tr")
.not(":first,:last")
.filter(":odd")
.addClass("someclass")
.css("border","solid 1px grey");
Note : I don't mean clientside script.My only concern is function chaining is possible in C# or not
Upvotes: 2
Views: 549
Reputation: 25523
Yes you need to look into using the Builder Pattern modified to return the object being worked on.
Example:
public class SomeClass
{
public SomeClass doSomeWork()
{
//do some work on this
this.PropertyA = "Somethign";
return this;
}
}
This is also referred to as a chaining design pattern.
Upvotes: 6
Reputation: 700592
Yes. I use it regularly, for example with a StringBuilder:
string s =
new StringBuilder()
.Append(year)
.Append('-')
.Append(month)
.Append('-')
.Append(day)
.ToString();
Or with my own library for creating HTML controls:
Container.Controls.Add(
Tag.Div.CssClass("item")
.AddChild(Tag.Span.CssClass("date").Text(item.Date))
.AddChild(Tag.Span.CssClass("title").Text(item.Title))
);
Upvotes: 1
Reputation: 467
Yes, and there are several good examples of how it can be done. For example, take a look at Fluent NHibernate.
Upvotes: 0
Reputation: 7722
You can call one function from another just like most programming languages... it all depends on how you build.
You could have an object as such:
public class DoMath
{
private int Add2(int piNumber)
{
return piNumber + 2;
}
private int Divideby7(int piNumber)
{
return Divideby7(this.Add2(piNumber));
}
}
Upvotes: 0
Reputation: 71238
yes, try this
var s = 19.ToString().Replace("1"," ").Trim().ToString("0.00");
Upvotes: 0
Reputation: 12478
Yes, you can, but as with jQuery, the functions you want to chain must be built for it. If you build your own, just return the object the caller should chain on. One example of chaining in C# is Fluent nHibernate.
Upvotes: 2
Reputation: 101251
Yes, just return the current object (this), and you can chain as much as you want. It's also called fluent interface
Upvotes: 9