I have 2 classes, each returns itself in all of the function:
public class Parent{
public Parent SetId(string id){
...
return this
}
}
public class Child : Parent{
public Child SetName(string id){
...
return this
}
}
I want to enable this kind of API:
new Child().SetId("id").SetName("name");
SetName
cannot be accessed since SetId
returns Parent
and SetName
is on the Child
.
How?
If you really want this fluent behavior, and the Parent
class can be made abstract, then you could realize it like this:
public abstract class Parent<T> where T : Parent<T>
{
public T SetId(string id) {
return (T)this;
}
}
public class Child : Parent<Child>
{
public Child SetName(string id) {
return this;
}
}
It is now possible to write:
new Child().SetId("id").SetName("name");
I might be missing the point here, but it looks like your really just trying to set properties. If you expose them as properties you can use an object initializer call.
var child = new Child()
{
Id = value1;
Name = value2;
}
You can also call a method instead of setting a value inside the intializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With