webworm
webworm

Reputation: 11019

Use of Nullable Type in method gives error

I have created a property within a class that is a nullable integer:

private int? submittedAge {get; set;}

I am doing this as the user may or may not enter an age. Later in the application I do a check before making use of this property, and if it is NOT null, I pass it along to a method that requires an integer.

if (this.submittedAge != null)
{
  result = utilityClass.GetPeopleWithMatchingAge(this.submittedAge);
}

Intellisense gives me an error saying the method call has some invalid arguments.

If I change the submittedAge property back to a non-Nullable integer then all is well.

Perhaps I am not understanding the proper use of a nullable type.

Upvotes: 2

Views: 86

Answers (2)

Allan Elder
Allan Elder

Reputation: 4104

if (this.submittedAge.HasValue)
{
   result = utilityClass.GetPeopleWithMatchingAge(this.submittedAge.Value);
}

or if you want to have your code handle a specific default value, you can do this

result = utilityClass.GetPeopleWithMatchingAge(this.submittedAge.GetValueOrDefault(-1));

in that case, if the user hasn't specified a value, submittedAge will return -1.

If you'd like to see what it is doing underneath the covers and why there is no explicit cast available, the source code is available here

Upvotes: 2

Selman Genç
Selman Genç

Reputation: 101731

It seems your method takes an int not int?, you need to change your parameter type or add an overload.

Or you can just pass the value using .Value property:

result = utilityClass.GetPeopleWithMatchingAge(this.submittedAge.Value);

Upvotes: 5

Related Questions