Check string is null or empty in linq - c#

I have string with empty space("________")
string MyNote= Convert.ToString(Session["MyNote"]);
if(MyNote!=null || MyNote != "")
{
}
MyNote != "" does not work if string has more space so
How can I check my string is "" or null by using linq in C#?

String.IsNullOrWhiteSpace is the method you're looking for.
Indicates whether a specified string is null, empty, or consists only of white-space characters.
Alternatively, using your idea:
if(MyNote!=null && MyNote.Trim() != "")
{
}
or
if(MyNote!=null && MyNote.Trim().Length == 0)
{
}

if(MyNote!=null || MyNote.Length > 0) //or you may want to set different value than 0
{
}

This works for me:
string MyNote = Session["MyNote"] == null ? String.Empty : Session["MyNote"].ToString();

Related

Adding String Length Validation

I am adding validation to my text string. It allows string and integer values, which is correct, but I want to require my text to be greater than 4 characters long. I've added the text.Length > 4 but this does not add any validation when entering a 2 character string. Any suggestions?
public bool IsStringInvalid(string text)
{
if (String.IsNullOrEmpty(text))
{
if (text != null && !Regex.IsMatch(text, textCodeFormat) && text.Length > 4)
{
return true;
}
}
return false;
}
Your method is called IsStringLengthInvalid, which implies that it should be returning true for invalid strings. Right now, it appears you're trying to return true only for valid strings.
Something like this should work:
public bool IsStringInvalid(string text)
{
return string.IsNullOrEmpty(text) ||
text.Length <= 4 ||
!Regex.IsMatch(text, textCodeFormat);
}
You are checking for not null condition nested inside the null condition which is logically wrong. You should do something like this.
public bool IsStringInvalid(string text)
{
if (text != null && text.Length > 4 && !Regex.IsMatch(text, textCodeFormat))
{
return true;
}
return false;
}
You have your length validation if statement nested inside your other if. If text has any data if will never reach the nested if as it will fail the first since IsNullOrEmpty will return false.
I would do something like
if (String.IsNullOrEmpty(text) || !Regex.IsMatch(text, textCodeFormat) || text.Length < 4)
{
return true;
}
return false;

Can't understand why if statement is running code for True test result

I have an IF statement that is supposed to make sure the TextBox1.Text and TextBox2.Text do not match or are not blank. If they don't match or are not blank then it is supposed to assign the text in the boxes to two string variable. What I can't figure out is why when I leave the two textboxes blank the true statement still fires.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
There are two conditions in your if statement:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
The first one checks to make sure they don't match (so, good). The second checks to make sure that they are blank (so, bad). You want this:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
Also, what are you trying to do? The second condition is the only one you need if you really want them not to match OR not be blank - because the only time this will be false is if they are both blank.
You wrote "OR textbox are blank", you need "OR textbox are not blank"
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
As a side note, I'd replace "" with string.Empty for readability.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
And for even more readability, you can extract these big conditions
if (TextboxesDoNotMatch() || TextboxesAreNotEmpty())
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
private bool TextboxesDoNotMatch()
{
return tbStartBreak2.Text != tbEndBreak2.Text;
}
private bool TextboxesAreNotEmpty()
{
return tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty;
}
If you want it to return that they are NOT blank then you need to do this
(tbStartBreak2.Text != "" && tbEndBreak2.Text != "")
you have an OR between both conditions so when both are empty the second part will be true regardless the first part
(tbStartBreak2.Text == "" && tbEndBreak2.Text == "")

Checking for null property

I want to check that a property on an array which is itself a child object is not null.
So i have
if (Parent.Child != null && Parent.Child[0] != null && Parent.Child[0].name != null)
var myName = Parent.Child[0].name
This seems like a very long winded way to get to the child[0].name whilst avoiding null reference exceptions. I am also getting index out of range errors. Is there a better way?
If you're getting IndexOutOfRangeException errors, that suggests that Parent.Child could be empty. So really you want:
if (Parent.Child != null && Parent.Child.Count > 0 && Parent.Child[0] != null &&
Parent.Child[0].name != null)
{
...
}
There's nothing that would simplify this very much, although you could write a version of LINQ's FirstOrDefault method which even coped with the source being null:
public static T NullSafeFirstOrDefault(this IEnumerable<T> source)
{
return source == null ? default(T) : source.FirstOrDefault();
}
Then:
var firstChild = Parent.Child.NullSafeFirstOrDefault();
if (firstChild != null && firstChild.name != null)
{
...
}
Your code appears OK apart from missing a test for the array being empty and is the correct defensive programming. You should extract this into a method to make it's intention clearer and your code here cleaner:
if (Parent.HasChild())
{
var myName = Parent.Child[0].name;
}
public bool HasChild()
{
return this.Child != null && this.Child.Count > 0 &&
this.Child[0] != null && this.Child[0].name != null;
}
The only other way would be to wrap the code in a try/catch block:
try
{
var myName = Parent.Child[0].name;
...
}
catch
{
}
However, this is bad programming practice as:
You are using exceptions to control program flow.
You are hiding other potentially serious errors.
try
var Names = new List<string>();
if(Parent.Child != null && Parent.Child.Count() > 0){
foreach(var item in Parent.Child) Names.Add(item.name)
}
var ParentChild= Parent.Child[0] ;
if (Parent.Child != null && ParentChild != null &&ParentChild.name != null)
var myName = ParentChild.name
Maybe simple try/catch will help?
var myName;
try
{
myName = Parent.Child[0].name;
}
catch (NullReferenceException)
{ myName = null; }

Checking multiple conditions in a single If statement - C#

I have a form in which there are many textBoxes from which three textboxes are required to fill in order to submit the form. I dont want to use each If block for each text box. Is there any way to use a single if statement for all the three text boxes? I am using the following code:
if (textBox1.Text != "" || textBox2.Text != "" || textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
but this code works even a single text fox is filled and the rest of the required text boxes are empty.
if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You want all conditions to pass. This fits the semantics of the logical AND operator &&.
If you have tons of textboxes, I would tend to keep them in a list:
var boxes = new List<TextBox>{
textBox1,
textBox2,
textBox3,
//...
};
if (boxes.Any(tb => string.IsNullOrEmpty(tb.Text)))
{
MessageBox.Show("Fill required fields");
}
else
{
// Code
}
I also tend to prefer to keep the exception in the if part, returning or throwing an error and ommit an else part, since that is just normal code flow. This keeps the code you expect to run as far to the left as possible.
You should change || to &&
You created a collection of or statements, so only one needs to be true in order to continue. Instead you need to and them:
if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")
You may define a method to test empty strings.
public class Test
{
public static bool IsEmpty(params string []args)
{
if (args.Length == 0) return true ;
return args.Any(p => string.IsNullOrEmpty(p));
}
}
To test strings,
if(!Test.IsEmpty(TextBox1.Text,TextBox2.Text,TextBox3.Text))
{
//valid
}
You use OR (||) and should use AND (&&) instead. You want ALL three textboxes to be non-empty strings. Check out the following code:
if (textBox1.Text != String.Empty && textBox2.Text != String.Empty && textBox4.Text != String.Empty)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You can also make a collection of TextBoxes and loop through them to check for non-empty Strings. Something like this:
List<TextBox> _lstTextBoxes = new List<TextBox>();
_lstTextBoxes.Add(textBox1);
_lstTextBoxes.Add(textBox2);
_lstTextBoxes.Add(textBox3);
Boolean checkFailed = false;
foreach(TextBox tb in _lstTextBoxes)
if(tb.Text == String.Empty)
checkFailed = true;
if(checkFailed)
MessageBox.Show("Fill required fields");
else
//code
This way you have a more generic approach to which you can easily add or remove certain textboxes.
Instead of using OR (||) use AND (&) in your condition.
Suggestion
Use Trim function from string to remove any white spaces from textbox (if required)
Instead of comparing like textBox1.Text != "" do String.IsNullOrEmpty(textBox1.Text) == false
Assuming you have 4 textboxes in total, below code will work
if ((textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "") || (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "") ||
(textBox1.Text != "" && textBox3.Text != "" && textBox4.Text != "") || (textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "")
)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}

checking filename

How can i check if filename contains some string? for example if "frody" contains "ro"?
I tried like that:
if (file_name.Contains("ro")== true)
and:
if (file_name.Contains("ro"))
Both are correct. The second is probably more favoured.
E.g., this returns true:
string s = "test-ro.doc";
Console.WriteLine(s.Contains("ro"));
if (s == null || s.Trim().Length == 0)
{
return false
}
else
{
return s.ToLower().Contains("ro");
}

Categories

Resources