Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot I use String.Contains() if default string is null?

Tags:

string

c#

.net

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.

like image 887
Tân Avatar asked Nov 27 '15 09:11

Tân


People also ask

Can string contains null?

contains() method does not accept 'null' argument. It will throw NullPointerException in case method argument is null.

Is default string 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.

Why use null instead of empty string?

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.

Does Isnull check for empty string?

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.


1 Answers

the new compilier allows you to do it with the condition check simplified.

string s = null;
Console.WriteLine(s?.Contains("Hello World!"));
like image 83
Mike Avatar answered Oct 20 '22 17:10

Mike