From MSDN doc:
public bool Contains(
string value
)
Return Value: true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.
Exception: ArgumentNullException: value is null.
Example:
string s = string.Empty; //or string s = "";
Console.WriteLine(s.Contains("Hello World!")); //output: False
If I change it to:
try
{
string s = null; //or string s;
Console.WriteLine(s.Contains("Hello World!"));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
It'll throw an error message: Object reference not set to an instance of an object
since string
doesn't have a default value (like ""
) from Default Values Table (C# Reference),
Please come back to the example, the code will work if I declare s
:
string s = "";
Now, Object s
is set to an instance of an object.
So, my question is: Does MSDN forgot something like: s
cannot be null?
To check it, I've tried:
string s = null;
Console.WriteLine(!string.IsNullOrEmpty(s) ? s.Contains("Hello World!") : false);
It should work.
contains() method does not accept 'null' argument. It will throw NullPointerException in case method argument is null.
The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.
If you were to use s , it would actually have a value of null , because it holds absolute nothing. An empty string, however, is a value - it is a string of no characters. Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
the new compilier allows you to do it with the condition check simplified.
string s = null;
Console.WriteLine(s?.Contains("Hello World!"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With