How can i get my application to accept null value  as valid

Olukayode Oluwole
Olukayode Oluwole used Ask the Experts™
on
I have a C#  application with a variable  selectedPeriod.mnthyear

I need to have the variable accept both regular values and Null

The test  script (attached)  is ok when there is a value.

When the value of the variable  is null  the application  reports an error as attached

What is wrong with my test syntax for   selectedPeriod.mnthyear  when it is null ?

Thanks

Olukay
HandlingNull16022019.PNG
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
I would use a try/catch block to trap these errors.
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
You should use Nullable Types https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/
double? pi = 3.14;
char? letter = 'a';

int m2 = 10;
int? m = m2;

bool? flag = null;

// Array of nullable type:
int?[] arr = new int?[10];

Open in new window

Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
Don't check for a property of selectedPeriod but for the object itself, thus:

If (selectedPeriod == null)
{
// <snip>

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Couple of points to clarify here.

When you are doing this:

if (selectedPeriod.mnthyear == null)

You are looking to check if the mnthyear property of the selectedPeriod object is null. The error you're getting is telling you that the selectedPeriod object is null. Because that's null, it throws and error and never actually gets to check the mnthyear property (you can't check the property of a null).

You should use the null-conditional operator here (the question mark), like so:

if (selectedPeriod?.mnthyear == null)

Now your check will return null if selectedPeriod is null. If it's not, then it will check the mnthyear. This will prevent the error you're getting, and match null if either selectedPeriod or mnthyear is null.
Olukayode OluwoleSystems Analyst

Author

Commented:
A big thank you to all the experts.

I believe any of the suggestions might have worked.

The solution from Chris Stanyon requiring only a  ?   appears easiest to implement

Once again thanks  for the help
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
But you don't use the property mnthyear in this part of the code, so easiest ..?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial