We help IT Professionals succeed at work.

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

Olukayode Oluwole
on
74 Views
Last Modified: 2019-02-16
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

David Johnson, CDSimple Geek from the '70s
CERTIFIED EXPERT
Distinguished Expert 2019

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

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
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
CERTIFIED EXPERT
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

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
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
CERTIFIED EXPERT
Most Valuable Expert 2015
Distinguished Expert 2018

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

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions