Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object oriented return type "this" on child call

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?

like image 420
SexyMF Avatar asked Oct 29 '11 13:10

SexyMF


Video Answer


2 Answers

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");
like image 193
Elian Ebbing Avatar answered Sep 20 '22 22:09

Elian Ebbing


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.

like image 36
rie819 Avatar answered Sep 20 '22 22:09

rie819