The Real World Functional Programming has this code in page 65.
The Tuple has two properties Item1 and Item2, and it has TupleExtensions class as follows.
static class TupleExtensions {
public static Tuple<T1, T2> WithItems2<T1, T2>
(this Tuple<T1, T2> tuple, T2 newItem2) { // line3 ???
return Tuple.Create(tuple.Item1, newItme2); // line4 ???
}
}
var pragueOld = Tuple.Create("Prague", 1188000);
var pragueNew = pragueOld.WithItem2(pragueOld.Item2 + 13195);
The pragueOld.WithItem2() has only one parameter, but the definition has two parameters.
I think line 3, 4 is the same as this code.
(T2 newItem2) {
return Tuple.Create(this.Item1, newItem2)
What’s the meaning of this as is prepended in the first parameter? What advantages does this provides compared to the simple this.Item1 usage?
the this keyword, in this context, means that you are declaring an extension method.
To declare an extension method you must be in the scope of a static class and the method must also be marked static.
This would be an example
and you could call this by either
or simply
an additional note: the “this” parameter can actually be null. Which isn’t that intuitive and it took me a while to realize, so you can either expect the function to fail if null is passed, or add null reference checks, like so: