2

I have the following C# code:

public interface IViewModel {
  PageData Page { get; set; }   
}

public class PageData { }

public class ViewModel<T> : IViewModel {

  public PageData PageData { get; set; }
  public T ViewData { get; set; }

  public ViewModel(T viewData, PageData pageData) {
    PageData = pageData;
    ViewData = viewData;
  }
}

Then I use it as follows:

PageData pd = new PageData();
ViewData vd = new ViewData();
ViewModel<MyViewData> model = new ViewModel<MyViewData>(vd, pd);

Is it possible to change my code so I can use it as:

IViewModel model = new ViewModel(vd, pd);

Basically ViewModel would take the type of vd.

3 Answers 3

3

No, but what you can do is provide a static factory method to make life easier:

public static class ViewModel
{
    public static ViewModel<T> Create<T>(T viewData, PageData pageData) 
    {
        return new ViewModel<T>(viewData, pageData);
    }
}

And use it like:

IViewModel model = ViewModel.Create(vd, pd);
Sign up to request clarification or add additional context in comments.

Comments

2

No, it's not possible. In C#, generics are not implemented by erasure, so every ViewModel you create has to know, at runtime, what its generic type is, at the moment it gets constructed. So the constructor needs to have its generic type, but you can still cast it as an IViewModel without generics.

IViewModel model = new ViewModel<MyViewData>(vd, pd);

As Alex points out, you can use a helper method that will infer the type of the first argument and use that generic type in its new expression.

Comments

0

You can make your MyViewData implement an Interface and then:

public class ViewModel : IViewModel {

  public PageData PageData { get; set; }
  public YOURINTERFACE ViewData { get; set; }

  public ViewModel(YOURINTERFACE viewData, PageData pageData) {
    PageData = pageData;
    ViewData = viewData;
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.