Paxsentry Paxsentry - 13 days ago 6
C# Question

Convert <T> into ViewModel

I was wondering is it possible to solve this problem in a bit more generic way.

Give two viewmodels nearly identical, the difference is in the naming (e.g. public string Description and public string ReviewDescription)
There is a comparing function which works like this:

private bool CompareTask(Models.Task model, TaskViewModel data)
{
bool same = false;
same = (model.Description == data.Description); // more compare
return same;
}


The question: is it possible - and if yes, how - to use generic for view model, something like this:

private bool CompareTask<T>(Models.Task model, T data)


and create an if statement like:

if (typeof(T) == typeof(TaskViewModel)){ ... }
else if (typeof(T) == typeof(TaskReviewModel)) { ... }

Answer

Why don't you use IEquatable<T>?

Implement it in your view models and models:

public class SomeViewModel : IEquatable<SomeModel>
{
    bool IEquatable<SomeModel>.Equals(SomeModel model)
        => model != null && SomeProperty == model.SomeOtherProperty;
}

Now, you can implement this method:

public bool AreEqual<T, S>(T a, S b)
     where T : class
     where S : class
{
    IEquatable<S> equatableToB = a as IEquatable<S>;

    return equatableToB != null && equatableToB.Equals(b);
}

You get a clear advantage with this approach: both a model or view model can be equatable with one or more classes:

public class SomeViewModel : IEquatable<SomeModel>, IEquatable<SomeOtherModel>
{
    bool IEquatable<SomeModel>.Equals(SomeModel model)
        => model != null && SomeProperty = model.SomeOtherProperty;


    bool IEquatable<SomeOtherModel>.Equals(SomeOtherModel model)
        => model != null && SomeOtherProperty = model.EvenSomeOtherProperty;
}