Click here to Skip to main content
16,004,574 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hi

I have
C#
s=new List<string>()

that returns
C#
""
when am using a breakpoint

Now I cant seem to validate
C#
"s"
using
C#
null


eg
C#
 if(result.s==null)
{
errorText="error"
}
else
{
//Play hangman code here
}


It always skip the if and jumps to else...
Posted
Comments
BillWoodruff 3-Oct-13 9:26am    
If you are using JavaScript with C# here, please state that, and explain that, in your question.

When you declare a Reference Type, it is null ... until you initialize it.

So when you declare: List<string> s; // 's is null

And, when you intialize 's: s = new List<string>(); // 's is not null, internal List has #0 elements.

You can check for both the case of 'null and internal List having #0 elements like this:
C#
if (s == null || s.Count == 0)
 {
     errorText = "error";
 }
 else
 {
     // playHangman(?, ? ... ?);
 }
This code takes advantage of the fact that at run-time .NET will evaluate the first logical term in an 'if statement OR test and return 'true if it evaluates to 'true without evaluating the second term of the OR test.

If you tried to access the Count Property of 's when it was declared, but not initialized, that would cause an error.

However, if you are certain you have initialized 's, then you can just use (s.Count == 0) for your test expression.
 
Share this answer
 
v2
Comments
Mehdi Gholam 3-Oct-13 9:38am    
"If" short circuit evaluation is done at runtime, not by the compiler, 5'ed
BillWoodruff 3-Oct-13 13:33pm    
Thanks, Mehdi, I've edited the text to reflect your feedback.
If you check for the value of s before it is being initialized, it will be null. Since "S" is instantiated using s=new List<string>(), it can't be null.

If you want to know if s has values in it you can simply check for s.count(). If the value is 0, it means there are no values in it.
 
Share this answer
 
Comments
Anele Ngqandu 3-Oct-13 9:03am    
s is accepting value from JavaScript, now JavaScript passed value of s=""
if(s.count()==0
{

}
else
{
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900