I'm trying to convert a view model to list and then return it to the view but am getting the cannot implicity convert type error.

Code:

public ActionResult Index(FeedEventCommand command)
{
    var feedEventViewModel = new FeedEventViewModel
    {
        AnimalId = command.AnimalId,
        AnimalName = command.AnimalName,
        FeederTypeId = command.FeederTypeId,
        FeederType = command.FeederType
    };
    feedEventViewModel = new List<feedEventViewModel>();  <--Error line

    return View(feedEventViewModel);
}

What am I doing wrong in this case?

2

There are 2 best solutions below

1
Tinwor On BEST ANSWER

feedEventViewModel is already declared as a single object, you can't declare it again as a List<FeedEventViewModel>(). Other language such as Rust allows you to "shadow" the variable declaration but C# not (and var is just a shorter way to declare a variable).
You can solve this issue quite easily:

return View(  new List<FeedEventViewModel>() {
    new FeedEventViewModel{
        AnimalId = command.AnimalId,
        AnimalName = command.AnimalName,
        FeederTypeId = command.FeederTypeId,
        FeederType = command.FeederType
       }
    }
    );
0
Chris On

You may be misunderstanding what the var keyword is doing here. When you declare a variable with var you are not saying that the variable can be anything, you are saying to the compiler that it can work out what the type is without you needing to specify it precisely.

So in your example (or a slight modification) when the compiler encounters the code:

var feedEventViewModel = new FeedEventViewModel();

it will see that the right hand side of the assignment is of type FeedEventViewModel and so the variable feedEventViewModel will be of that type. In effect it will be like you typed:

FeedEventViewModel feedEventViewModel = new FeedEventViewModel();

Any later use of that variable must be in line with this declaration so when you do feedEventViewModel = new List<feedEventViewModel>(); the compiler rightly says that List<feedEventViewModel> is not of the type expected by feedEventViewModel. There is such a thing as implicit conversions whereby the compiler knows how to convert between two different types and is allowed to do it without it being specifically requested but no such implicit conversions were found, hence the error.

It is unclear from the information given what exactly you are doing (is the item you created meant to be on the list? Does your view expect a list or a single item?). If you need a list with the item in then I'd just go with:

var list = new List<feedEventViewModel>(){feedEventViewModel };
return View(list);