I’m looking at a tutorial for asp.net mvc here on the asp site: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application
There is a method in the controller that has me confused:
//
// GET: /Student/Delete/5
public ActionResult Delete(int id, bool? saveChangesError)
{
if (saveChangesError.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists contact your system administrator.";
}
return View(db.Students.Find(id));
}
I’m seeing that a bool is created called ‘saveChangesError’, but in the if statement, there is a method being called on the boolean called ‘GetValueOrDefault()’
What exactly is going on in this scenario? I’m assuming that GetValueOrDefault() must be a method of all boolean types? I looked this up in the .NET documentation and found this definition:
The value of the Value property if the HasValue property is true;
otherwise, the default value of the current Nullable(Of T) object. The
type of the default value is the type argument of the current
Nullable(Of T) object, and the value of the default value consists
solely of binary zeroes.
I’m having trouble connecting this definition with what is going on the the .net mvc app.
Thanks.
GetValueOrDefault()isn’t part of thebool, it’s part ofNullable<T>. The key here is the syntax where theboolis declared in the function header:The question mark is a C# language construct which indicates that this isn’t really a
bool, but is aNullable<bool>. Value types, of whichboolis one, can’t benull. But sometimes it would be useful if they could. So theNullable<T>struct exists to serve that purpose.GetValueOrDefault()is a method on that struct which will return the value of theboolor the default value for abool(which isfalse) if no value is specified.