vs2005 c#
string var = string.Empty;
why "76090,76091,76092,G0202,G0204,G0206".IndexOf(var)
returns 0 ?

should be -1 for not found...empty is not part of my string being searched
any ideas
thanks

Re: indexOf question by Chris

Chris
Thu May 08 12:55:01 CDT 2008

raulavi wrote:
> vs2005 c#
> string var = string.Empty;
> why "76090,76091,76092,G0202,G0204,G0206".IndexOf(var)
> returns 0 ?
>
> should be -1 for not found...empty is not part of my string being searched
> any ideas
> thanks

This was literally *just* discussed a couple threads back:
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/6343be990c83f93f#

Chris.

RE: indexOf question by MortenWennevik

MortenWennevik
Fri May 09 00:05:00 CDT 2008

Hi,

In case you want to test for an empty string use

if(string.IsNullOrEmpty("Hello World"))
{
// string is either null or ""
}

--
Happy Coding!
Morten Wennevik [C# MVP]


"raulavi" wrote:

> vs2005 c#
> string var = string.Empty;
> why "76090,76091,76092,G0202,G0204,G0206".IndexOf(var)
> returns 0 ?
>
> should be -1 for not found...empty is not part of my string being searched
> any ideas
> thanks

Re: indexOf question by Mythran

Mythran
Fri May 09 12:49:17 CDT 2008



"Morten Wennevik [C# MVP]" <MortenWennevik@hotmail.com> wrote in message
news:E6732861-719B-4B22-91F3-4C16267136FF@microsoft.com...
> Hi,
>
> In case you want to test for an empty string use
>
> if(string.IsNullOrEmpty("Hello World"))
> {
> // string is either null or ""
> }
>
> --
> Happy Coding!
> Morten Wennevik [C# MVP]

I would be hard pressed to use IsNullOrEmpty to check for an empty string.
This is due to the fact that Null means the absence of a value while an
empty string is a string whose value contains no characters (hence empty
string). IsNullOrEmpty is the same as:

("Hello World" == null || "Hello World" == string.Empty)

while checking for an empty string is:

("Hello World" == string.Empty)

Therefore, they are not functionally equivalent. Although, I would usually
use IsNullOrEmpty in place of just an empty string check in *most* cases.
Some cases, you may not want to check for null, maybe you need to do
something different for null strings (raise an exception?) compared to empty
strings (allowed so no exception?).

HTH,
Mythran