Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor my code : Avoiding casting in derived class

Tags:

c#

refactoring

Firstly, I feel sorry about the title, I do not know how to describe my problem exactly. I hope it will be better explained through the code.

public abstract class AB {
  public MyModel Model;
}

public class A : AB {
  public A() {
    Model = new MyModelA();
  }

  public void AMethod() {
    var model = (MyModelA) model; // I have to do this all place
  }

  public void AnotherMethod() {
    var model = (MyModelA) model; // same here
    model.NewInt = 123;
  }
}

public abstract class MyModel {

}

public class MyModelA : MyModel {
  // new properties
  public int NewInt {get;set;}
}

Take a look at the code, in order to use new properties from derived class, I have to do a cast but it is ugly when I have to use it same time all over places.

The method I think is declare another property: public MyModelA _tmp then I cast it in the constructor _tmp = (MyModelA) Model and use it instead of Model.

Are there any other appropriate ways to do this ? Thanks !

like image 555
Dzung Nguyen Avatar asked Aug 25 '26 06:08

Dzung Nguyen


1 Answers

You can make the base class generic:

public abstract class ServiceBase<TModel> where TModel : new() {
    protected ServiceBase() { Model = new TModel(); }
    public TModel Model { get; private set; }
}

public class AService : ServiceBase<MyModelA> {
    ...
}
like image 65
SLaks Avatar answered Aug 27 '26 19:08

SLaks



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!