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 the bool
, it's part of Nullable<T>
. The key here is the syntax where the bool
is declared in the function header:
public ActionResult Delete(int id, bool? saveChangesError)
The question mark is a C# language construct which indicates that this isn't really a bool
, but is a Nullable<bool>
. Value types, of which bool
is one, can't be null
. But sometimes it would be useful if they could. So the Nullable<T>
struct exists to serve that purpose.
GetValueOrDefault()
is a method on that struct which will return the value of the bool
or the default value for a bool
(which is false
) if no value is specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With