Share via

How to reduce code with generic T?

Emon Haque 3,176 Reputation points
2020-10-24T17:26:12.61+00:00

To reduce code and complexity, I've been using abstract class for a while and recently I've added T into it to reduce more. Here's an excerpt from an abstract class:

public abstract class EditBase<T> : Notifiable where T: new()
{
    protected T selected;
    public T Edited { get; set; }

    protected abstract void clone();
    protected abstract bool isCloneNotOriginal { get; }
}

all edit ViewModels needs a selected and an Edited objects and the base, with the T, provides that to all. When I get into edit mode in my views, I need a clone of selected and before saving the clone (Edited), I check whether selected and Edited are equal or not. To do these, in all of my Models, I've added a copy contructor for deep copy and a function, IsEqualTo, to check value equality. Here's what I've in a child class:

public class EditPlotVM : EditBase<Plot>
{
    protected override void clone()
    {
        Edited = new Plot(selected);
        OnPropertyChanged(nameof(Edited));
    }
    protected override bool isCloneNotOriginal => !Edited.IsEqualTo(selected);
}

and I've same thing in overridden clone and isCloneNotOriginal in all of my edit ViewModels. I want to remove these from child classes and have these in base abstract class. So to do that, I'd tried these:

void clone()
{
    Edited = new T(selected);
    OnPropertyChanged(nameof(Edited));
}
bool isCloneNotOriginal() => !Edited.IsEqualTo(selected);

in the base class BUT none worked! Edited = new T(selected) in clone and !Edited.IsEqualTo(selected) in the other function gives me error!

What do I have to have in the new() constraint to force it to take selected when I new up and what do I have to do to let T know that T has a function named IsEqualTo?

Developer technologies | Windows Presentation Foundation
0 comments No comments

1 answer

Sort by: Most helpful
  1. Emon Haque 3,176 Reputation points
    2020-10-24T19:27:22.857+00:00

    Not sure whether this is the only way, with this:

    public interface IEditable<T>
    {
        public T Clone(T source);
        public bool IsEqualTo(T source);
        public bool IsValid();
    }
    

    I'd to turn the copy constructor into a function in my Models and replace the constraint with IEditable<T>, new() in base class. Not bad!

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.