Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 - How is this boolean value working in the controller?

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.

like image 998
PhillipKregg Avatar asked Dec 21 '22 00:12

PhillipKregg


1 Answers

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.

like image 60
David Avatar answered May 03 '23 07:05

David