0

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?

rethabile
  • 3,029
  • 6
  • 34
  • 68
  • In this question you can understand the three types: [link](http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var) – Davi Ruiz May 16 '13 at 21:46

2 Answers2

2

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.

Colm Prunty
  • 1,595
  • 1
  • 11
  • 29
0

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).

Russ Cam
  • 124,184
  • 33
  • 204
  • 266