Difference between "" (Empty String) and isNot Nothing? - c#

I am working on a condition where I have to validate whether the argument is empty or not. Lets assume that argument is Email. I have to check whether the inwards argument Email is empty or not. I can do it in several way but I am not sure which one to proceed with.
I am thinking to check from following statement:
1.Email = "" to check if email is empty string or not.
2. Email isNot Nothing
I wanna know the difference of these two functionality. If there are more function or argument related to validating empty string, You can write that too.
Thanks.

String is a reference type, which means it can have a null reference
Eg
string myString = null;
It can also be empty, which is to say, there is a reference to it, and it has 0 character length
Eg
string myString = "";
// or
string myString = string.Empty;
And just for completeness, it can also have white space
Eg
string myString = " ";
You can check for null like so
if(myString == null)
You can check for empty
if(myString == "")
// or
if(myString == string.Empty)
You can check for both, not null and not empty
if(myString != null && myString != string.Empty)
You could use Null conditional Operator with Length to check both is not null and not empty
if(myString?.Length > 0)
Or you can use the built in string methods, to make it a little easier
String.IsNullOrEmpty(String) Method
Indicates whether the specified string is null or an empty string
("").
if(string.IsNullOrEmpty(myString))
String.IsNullOrWhiteSpace(String) Method
Indicates whether a specified string is null, empty, or consists only
of white-space characters.
if(string.IsNullOrWhiteSpace(myString))
Note : It's worth noting, that IsNullOrWhiteSpace generally more robust when checking user input

Actually in C# string.Empty is equivalent to "". See String.Empty
Best way to check for Empty or Null strings is:
string.IsNullOrEmpty(Email) or you can use string.IsNullOrWhiteSpace(Email) to additionally check for white spaces.
if(!string.IsNullOrEmpty(Email))
{
// Good to proceed....
}

You should not use IsNot nothing with reference type variable. Instead, Use string.IsNullOrEmpty(Email) together with String.IsNullOrWhiteSpace(Email) while you need to validate email.

Related

Check if string does contain text C#

I want to find a way to check if a string contains text and if it does it will go to to the next one and keep doing this till it finds an empty string or reached the end.
The issue is I can't find anything that I could use to check if the string is containing any text, I can only find if it a IsNullOrWhiteSpace or if it contains a specific text.
When does a string contain text? Well when the string exists and it does not contain an empty text. When does a string contain an empty text? When the length of the string is 0.
So, answering your question, a text is not empty when it exists and s.Length != 0:
if (s != null && s.Length > 0) { /*s is not empty*/ }
or better yet
if (s?.Length > 0) { /*s is not empty*/ }
or if you prefer a string contains text when it is not nonexistant or empty:
if (!string.IsNullOrEmpty(s)) { /*s is not empty*/ }
Now if texts consisting only of whitespaces must also be considered as empty, then when is a text not empty? When the text is anything but nonexistant or empty spaces, that is, IsNullOrWhiteSpace is false:
if (!string.IsNullOrWhiteSpace(s)) { /*s is not empty*/ }

Verify empty field Selenium C#

I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}

C# Replace is causing Object Reference Not Found error

using "Replace" on the string clientNameStr causes an "Object Reference Not Found" error.
// Get client name
clientName = currentUser.GetValue("ClientName");
string clientNameStr = (string)clientName;
string clientURLStr = string.Empty;
clientURLStr = clientNameStr.Replace(' ', '-');
// clientURLStr = "ST9215-Stanic-Parts-Ltd";
If I substitute in the commented out string (and comment out the existing one) it works fine, so it must be something to do with the replace function, but what? Have tried it with both " and ' quote marks, to the same result.
Any help would be greatly appreciated.
Thanks, Oli.
That basically shows that currentUser.GetValue("ClientName") is returning a null reference1.
We can't tell what currentUser.GetValue("ClientName") does, but there are two options:
It's correctly returning null, and you should handle that
It shouldn't return null, and you need to fix it (possibly to throw an exception if it encounters this situation)
1 It's possible that it's returning a non-null reference and using a user-defined conversion to string in the next line which returns null - but unlikely. We can't tell for sure because we don't know the type of the clientName .
Probably clientName (and thus clientNameStr) is null. You cannot call methods on the null object, even if you know that it should be a string.
It's possible that currentUser.GetValue("ClientName") is returning null, thus throwing an error when trying to execute the Replace.
Better coding would be
clientName = currentUser.GetValue("ClientName");
string clientNameStr = clientName ?? "";
string clientURLStr = clientNameStr.Replace(' ', '-');

.Trim() when string is empty or null

I'm receiving some data from the client in the form of json.
I'm writing this:
string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
If the variable that's being parsed from json comes back empty, does this code crash when I call the .Trim() method?
Thanks.
You can use elvis operator, also known as "null-conditional-operators":
GetNullableString()?.Trim(); // returns NULL or trimmed string
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
If the serializer returns an empty string, Trim will do nothing.
If the serializer returns null, you will get a NullReferenceException on the call to Trim.
Your code would be better written (as far as initialization is concerned) like this:
string theText =
((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
There is no point in declaring and initializing the variable and the immediately assigning to it.
The following would be safest, if you don't know what the serializer might return:
string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));
if(!string.IsNullOrEmpty(theText))
{
theText = theText.Trim();
}
Calling Trim() on an empty string will result in an empty string. Calling Trim() on null will throw NullReferenceException
If you have a few fields you wish to trim but your getting exceptions for those records that have nulls in certain fields, then writing a quick extension method will be the easiest method:
public static class ExtensionMethods
{
public static string TrimIfNotNull(this string value)
{
if (value != null)
{
return value.Trim();
}
return null;
}
}
Sample example of use:
string concatenated = String.Format("{0} {1} {2}", myObject.fieldOne.TrimIfNotNull(), myObject.fieldTwo.TrimIfNotNull(), myObject.fieldThree.TrimIfNotNull());
Some basic techniques to check strings against null before you trim:
(mystring ?? "").Trim()
The "null coalescing operator" ?? will return the first operand. Only when this operand is null, the second operand will be returned (as a kind of default value).
The above example will return an empty string if mystring is null.
mystring?.Trim()
The "null conditional operator" ? will short cirtuit a chain of operations in dot-notation. If the operand is null, the following operations will not be executed and null will be returned.
The above example will return null if mystring is null.
if( string.IsNullOrWhiteSpace(mystring) ) { ... }
the IsNullOrWhiteSpace() method may replace trimming if you actually want to check if there is real content in mystring. It returns true if the operand is null, empty, or nothing but whitespace characters.
As suggested in some of the comments, you may now use c# 6 Null-conditional operators with this syntax:
string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();
Documentation: https://msdn.microsoft.com/en-us/library/dn986595.aspx
No, it would not be better to initialize TheText to "". You're assigning to it right afterwards.
No, it won't crash – Trim() works just fine on an empty string. If by "empty" you mean that it can be null, then yes, it will crash; you could have null remain null with a null-conditional call:
string TheText =
serializer.ConvertToType<string>(dictionary["TheText"])?.Trim();
You can use the null-safe operator trim of org.apache.commons.lang
StringUtils.trim(stringOrNull)
You can use this code as beblow
string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();
Recently I had to check a string if it is null, empty or whitespace using just one if condition and for that I found out that you can add "" to a null string to make it non null.
string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception
So I did this instead
string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true

Determine if string is newline in C#

I am somehow unable to determine whether a string is newline or not. The string which I use is read from a file written by Ultraedit using DOS Terminators CR/LF. I assume this would equate to "\r\n" or Environment.NewLine in C#. However , when I perform a comparison like this it always seem to return false :
if(str==Environment.NewLine)
Anyone with a clue on what's going on here?
How are the lines read? If you're using StreamReader.ReadLine (or something similar), the new line character will not appear in the resulting string - it will be String.Empty or (i.e. "").
Are you sure that the whole string only contains a NewLine and nothing more or less? Have you already tried str.Contains(Environment.NewLine)?
The most obvious troubleshooting step would be to check what the value of str actually is. Just view it in the debugger or print it out.
Newline is "\r\n", not "/r/n". Maybe there's more than just the newline.... what is the string value in Debug Mode?
You could use the new .NET 4.0 Method:
String.IsNullOrWhiteSpace
This is a very valid question.
Here is the answer. I have invented a kludge that takes care of it.
static bool StringIsNewLine(string s)
{
return (!string.IsNullOrEmpty(s)) &&
(!string.IsNullOrWhiteSpace(s)) &&
(((s.Length == 1) && (s[0] == 8203)) ||
((s.Length == 2) && (s[0] == 8203) && (s[1] == 8203)));
}
Use it like so:
foreach (var line in linesOfMyFile)
{
if (StringIsNewLine(line)
{
// Ignore reading new lines
continue;
}
// Do the stuff only for non-empty lines
...
}

Categories

Resources