Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling a fluent design in c# objects

Tags:

c#

fluent

I have a line of C#:

cats.Add(new Cat("happy") { Mean=false})

I with to modify the Cat and then apply the mean like this:

cats.Add(Fix(new Cat("happy")) { Mean=false})

but I can't. How what should the Fix() method do in order for the above to work?

like image 894
Ian Vink Avatar asked May 03 '26 14:05

Ian Vink


1 Answers

It won't work like that. The new X() { } is an initializer, and you can't split it up by calling a Fix around the constructor then the property / field bindings on the result. Property / field bindings must be evaluated before calling the Fix function.

You'd have to do this:

public Cat Fix(Cat cat) { ... }

cats.Add(Fix(new Cat("happy") { Mean=false }));

Or an extension method like this:

public static class CatExtensions {
     public static Cat Fix(this Cat cat) { ... }
}

cats.Add(new Cat("happy") { Mean=false }.Fix());

Or if you are a little more adventurous, you can accept an dynamic type:

public Cat Fix(Cat cat, dynamic properties) { ... }

cats.Add(Fix(new Cat("happy"), new { Mean=false }));

// extension method:
public static class CatExtensions {
     public static Cat Fix(this Cat cat, dynamic properties) { ... }
}

cats.Add(new Cat("happy").Fix(new { Mean=false }));

Or a generic method:

public Cat Fix<T>(Cat cat, T properties) { ... }

cats.Add(Fix(new Cat("happy"), new { Mean=false }));

// extension method:
public static class CatExtensions {
     public static Cat Fix<T>(this Cat cat, T properties) { ... }
}

cats.Add(new Cat("happy").Fix(new { Mean=false }));
like image 142
p.s.w.g Avatar answered May 06 '26 03:05

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!