devfric
devfric

Reputation: 7512

How to set the base class property of a generic class

I have a base class:

public abstract class MyBaseClass
{
    public string  MyProperty { get; set; } 
}

and then a class that gets passed a Generic class that get passed a TViewModel that inherits from MyBaseClass

public abstract class MyGenericController<TViewModel> : Controller
    where TViewModel :  MyBaseClass
{
    public virtual async Task<IActionResult> Index()
    {
        object viewModel = Activator.CreateInstance(typeof(TViewModel));
        viewModel.MyProperty="test";
        return View(viewModel);
    }
}

This works like I want it. However as soon as I try set the base class property I get a compile error:

object does not contain a definition for MyProperty on the line

viewModel.MyProperty="test";

How do I set the property?

Upvotes: 4

Views: 583

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Use the generic Activator.CreateInstance<T> instead:

public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = Activator.CreateInstance<TViewModel>();
    viewModel.MyProperty="test";
    return View(viewModel);
}

An alternative can also be to constraint the generic type parameter (which saves you the overhead of reflection) to contain a default constructor via TViewModel : MyBaseClass, new(), and then:

public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = new TViewModel();
    viewModel.MyProperty="test";
    return View(viewModel);
}

Upvotes: 6

Related Questions