Reputation: 3199
Cracking my head with MVC here.
I've written my model as:
public class AboutModel
{
public string AboutText { get; set; }
}
and my controller as:
public ActionResult About()
{
var model = new AboutModel { AboutText = "We build better software."};
return View(model);
}
and changed the new
line to:
AboutModel model = new AboutModel { AboutText = "We build better software."}
and finally to:
dynamic model = new AboutModel { AboutText = "We build better software."}
seems all works perfectly well with my View
:
@model MvcApp.Models.AboutModel
<p>@if (Model != null)
{
@Model.AboutText
}</p>
Any difference on my 3 model Initializations?
Upvotes: 0
Views: 244
Reputation: 1620
var model = new AboutModel
is an implicitly typed variable, in that you don't have to specify in advance what type your variable is, the compiler can infer it by what comes after the =. (in this case AboutModel
)
If you use an implicityly typed variable, you have to give it a value, for example:
var model = new AboutModel;
will compile, but
var model;
won't.
AboutModel model = new AboutModel
is specifying the type in the variable declaration, which you don't really need to do if you're giving it a value in the same line. If you give it a type on declaration, you don't need to give it a value. For example:
AboutModel model;
will compile.
The dynamic
keyword means it won't be type-checked at compile time, which won't make any difference in this case either.
Upvotes: 2
Reputation: 125528
No, the runtime type in all three cases is MvcApp.Models.AboutModel
.
In the first two cases you are passing the type as is and in the last case, passing it as dynamic, which will be attempted to be cast to the type for the view as defined by the @model
directive.
I would stick to one of strong type initializations for clarity, unless you need "dynamicity" (in which case you would want to set the @model
type to dynamic
too).
Upvotes: 0