Reputation: 333
This is mostly a syntax question. Here's a related thread showing different alternatives to achieve the same result: Method-Chaining in C#
Now, in C++ it is possible to chain commands on an object by making methods return the pointer to the object of which the method is a member.
The syntax I'm looking for is:
foo.Transform(bar).TransformDifferently(yay);
In C#, if I return this, the value is copied (edit: half incorrect, read answers). I don't think I can return a reference or a pointer, can I? Is there any other way to achieve the same syntax?
For now my solution is to just assign the result to my object, like so:
foo = foo.Transform(bar).TransformDifferently(yay);
It's however not the optimal solution, because it's both slower (doesn't matter in my case) and more verbose. I'd be very happy for any pointers in the right direction!
Upvotes: 2
Views: 333
Reputation: 2289
What type is your foo variable? Is it a class or a struct instance?
If it is a class instance, you can achieve the syntax you're looking for by returning 'this'. The object will not be copied. 'this' is a reference, exactly as you expect.
If foo is a struct instance, then what you're trying to achieve is a bad idea. It is recommanded to make structs immutable so we can reason about them like primitives (integers, booleans, etc.). You'd better return a copy in this case.
Upvotes: 0
Reputation: 149050
In C#, if I return this, the value is copied
This is not true, at least for classes. Classes in C# are reference types, that means every variable of that type is actually a reference, so returning this
just returns a reference to the current instance.
So to do this, it's essentially the same in C#:
public class Foo
{
public Foo Transform(Bar bar)
{
// transform
return this;
}
public Foo TransformDifferently(Yay yay)
{
// transform
return this;
}
}
For value types, it should return a new instance of the type. Value types are supposed to be immutable, so if you've designed your struct
correctly, there should be no method which modifies the original. Transform
should modify a new version of the struct instead.
Upvotes: 1
Reputation: 22955
In C#, if I return this, the value is copied
Incorrect. The this pointer refers to the 'current' object, and it does not create a deep or shallow copy of the object.
So this:
foo.Transform(bar).TransformDifferently(yay);
works fine.
Upvotes: 0