This question already has answers here:
Why does "abcd".StartsWith("") return true?
(11 answers)
Closed 9 years ago.
I jumped into this accidentally and have no clue as to why this is happening
string sample = "Hello World";
if (sample.Contains(string.Empty))
{
Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
Console.WriteLine(sample.LastIndexOf(string.Empty));
Console.WriteLine(sample.Length);
}
Output
This contains an empty part ? at position 0
10
11
I am happy with the last part, but i have no idea why this is evaluated true. Even Indexof and LastIndexOf have separate values.
Could anyone help me out on why is this so?
EDIT
I believe this is a bit relevant to my question and would be also helpful to those who stumble upon this question.
See this SO link: Why does "abcd".StartsWith("") return true?
From msdn for IndexOf
If value is String.Empty, the return value is 0.
For LastIndexOf
If value is String.Empty, the return value is the last index position in this instance.
For Contains
true if the value parameter occurs within this string, or if value is the empty string ("");
Question: Does the string "Hello World" contain String.Empty?
Answer: Yes.
Every possible string contains String.Empty, so your test is correctly returning true.
If you are trying to test if your string is empty, then the following code is what you want
if (string.IsNullOrEmpty(sample))
{
}
This is documented in the String.Contains Method:
Return Value
Type: System.Boolean
true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.
And in String.IndexOf Method
If value is String.Empty, the return value is 0.
And in LastIndexOf Method
If value is String.Empty, the return value is the last index position in this instance.
Related
I'm trying to understand CompareTo() in C# and the following example made me more confused than ever. Can someone help me understand why the result for the 3rd variation is 1? 2nd word in the sentence "Hello wordd" is not the same as str1 "Hello world" so why am I getting 1? Shouldn't I get -1?
static void Main(string[] args)
{
string str1 = "Hello world";
Console.WriteLine(str1.CompareTo("Hello World"));
Console.WriteLine(str1.CompareTo("Hello world"));
Console.WriteLine(str1.CompareTo("Hello wordd"));
}
Results: -1, 0, 1
If the strings match, then CompareTo() gives 0. If they don't match, it gives a positive or negative number depending on which string comes first alphabetically.
In your example, both the results 1 and -1 indicate the strings do not match, while 0 indicates the strings match.
It looks like you are using it to determine equality and not to sort. If this is the case, then you should use Equals() instead.
The String.CompareTo method compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes.
if the return value is Less than zero: This instance precedes value.
if the return value is Zero: This instance has the same position in the sort order as value.
if the return value is Greater than zero: This instance follows value.
-or-
value is null.
the most of the time when I work with C# and need to validate a null or empty string I use the method:
if (String.IsNullOrEmpty(s))
return "is null or empty";
else
but now I need to use this in this way:
string value= data.value==null?DBNull.Value:data.value;
I try to use both in the last sentence getting this
string value= String.IsNullOrEmpty(data.value)?DBNull.Value:data.value;
but always return true even is there is not any value in the property data.value, BTW data.value is a string, could you please tell me if my sentence is right or what seems to be the problem?
First off you cant use string value = DBNull.Value because those types are not compatible. You have to cast back to the common type which is System.Object so then the assignment becomes this which uses casting to ensure type compatibility:
object value = String.IsNullOrEmpty(data.value)
? (object) DBNull.Value
: (object) data.value;
If you want to check for white space you can use IsNullOrWhiteSpace instead of IsNullOrEmpty
There are many questions discussing this topic with ref to Javascript; but I could not get any with ref to C#.
Both the 'String........' statements below return false.
// foll querystring value from JQuery/Ajax call
var thisfieldvalue = Request.QueryString["fieldvalue"];
bool boola = String.IsNullOrWhiteSpace(thisfieldvalue );
bool boolb = String.IsNullOrEmpty(thisfieldvalue );
What is the best way to check for Undefined string variable in C#?
Note:
I get 'Undefined variable' values occasionally, via the JQuery/Ajax calls with the 'querystring'; and it ends up in the C# variable when I use the statement
var thisfieldvalue = Request.QueryString["fieldvalue"];
and the 'thisfieldvalue' variable passes both the 'String.IsNullOrWhiteSpace' as well as the 'String.IsNullOrEmpty' checks....
Note 2: I have edited the question again to make my question clearer... I am sorry that earlier it was not that clear....
you could use either
string Undefined_var = "[value to test goes here]"; //note that string must be assigned before it is used
bool boola = String.IsNullOrWhiteSpace(Undefined_var);
//or
bool boolb = String.IsNullOrEmpty(Undefined_var);
Difference being that IsNullOrWhiteSpace will check everything that IsNullOrEmpty does, plus the case when Undefined_var consists of only white space. But since a string consisting of only white space characters is not technically undefined, I would go with IsNullOrEmpty of the two.
But do note that since string is a reference type, the default value is null; so if you wanted to narrow down a step farther to eliminate the test for an empty string, you could do something like this-
string Undefined_var = null;
bool boola = Undefined_var == null;
There are no "undefined" string variables in C#.
String is a reference type, therefore if you don't define a value, it's default value is null.
There is no difference between a string not set to a value (default value null) and a string explicitely set to null.
In Visual Studio 2013 your code doesn't even compile. The first check gets flagged as use of unassigned local variable.
As C# is a strongly typed language, use it to your advantage, set the value explicitly:
string Undefined_var = null;
bool boola = String.IsNullOrWhiteSpace(Undefined_var);
bool boolb = String.IsNullOrEmpty(Undefined_var);
Then you will get two true values.
It question is not applicable to C# because C# does not allows a non-defined local variables. Members of classes are initialized by a member's default value (for reference types - initialized by null).
if (Request.QueryString["fieldvalue"] == "undefined")
It's a string, it will come across literally as a string.
If it is 5 it's a string of 5
If it is not there it's a string of undefined
Why does
Convert.ToBoolean("1")
throw a System.FormatException?
How should I proceed with this conversion?
Yes, this is as documented:
[throws] FormatException [if] value is not equal to TrueString or FalseString.
TrueString is "True" and FalseString is "False".
If you want to detect whether a string is "1" or not, use this code:
bool foo = text == "1";
Depends on what you want. Perhaps
var result = Convert.ToInt32(yourstirng) != 0
assuming any number but 0 is true. Otherwise a simple comparison would work.
var result = yourstirng == "1"
The parameter must be equal to either Boolean.TrueString or Boolean.FalseString. The values of these strings are "True" and "False", respectively. See MSDN.
The string value "1" is obviously not equal to "True" or "False".
The problem is, that youre giving a String here, not a number. It cant convert the String "1" to true, but the int 1.
Convert.ToBoolean(1);
should work.
When converting to Boolean it is best to use your own routine, where you handle all cases. .net Convert.ToBoolean isn't a practical routine, it is one of those function where you have to explain why it doesn't work.
I know this is old, but in case someone searches... simply do this:
Convert.ToBoolean(Convert.ToInt16("1")) works just fine. Not pretty, but needs be.
Another solution is to use an Extension Method on the string object. I used this technique in a case where I had to parse CSV files that had different strings that had to be converted to boolean values depending on their source and format.
public static class StringExtensions
{
public static bool ToBool(this string value,string trueValue)
{
if (value == trueValue)
{
return true;
}
else
{
return false;
}
}
}
This would be called like so...
MyProperty = CsvColumn[6].ToBool("1");
If you want, the truevalue parameter could be a string array if you needed to compare multiple values (like n/a, na, none) and you could add in false values if you want to further restrict it or use nullable types.
I have this piece of code in c#:
private static void _constructRow(SqlDataReader reader, system.IO.StreamWriter stwr, bool getColumnName)
{
for (int i = 0; i < reader.FieldCount; i++)
stwr.Writeline(String.Format("<td>{0}</td"), getColumnName ? reader.GetName(i) : reader.GetValue(i).ToString()));
}
I'm trying to understand what the part that start with "getColumnName ?" and ends with ".ToString()" does. I understood that it is a system.object type, but I have no idea what it specifically does or how it works.
I want that because of this: "reader" had multiple rows in it, and I want to writeline only specific rows.
If anyone can help me on either of those, I'd be grateful.
This is a conditional operator. It says if getColumnName is true, then use reader.GetName(i) otherwise use reader.GetValue(i).ToString()
The format is this:
ThingToCheck ? UseIfCheckIsTrue : UseIfCheckIsFalse
In the code, it looks like getColumnName is true for the header row, so it's outputting the column name and called again for all other rows using false, to output the values.
The function iterates over all columns in the data reader, then for each one:
If getColumnName returns true, it outputs the name of the column between the <td> tags, otherwise the value of the data.
To de-construct further:
reader.GetName(i) - this returns the name of the column
reader.GetValue(i).ToString() - this returns the value of the column as a string
getColumnName - a function the will return true if a column name can be gotten
?: - the conditional operator. If the expression before the ? is true, the expression to the left of the : is used, otherwise the one on the right
String.Format("<td>{0}</td", arg) - this will output "<td>arg</td>" (btw - your code is wrong, the ) should not be just after the first string)
That is called a conditional operator.
The argument getColumnName is evaluated and if true, the first argument after the ? is returned, if false, the second.
So, if getColumnName==true, you are going to see <td>NAME</td> else <td>Value</td>
Make sense?
It is like following
if (getColumnName == true)
{
reader.GetName(i); // GetName is string so no need to convert this in string I.E ToString()
}
else
{
reader.GetValue(i).ToString(); // GetValue returns object so this needs to convert in string using .ToString()
}
Because getColumnName is of bool type so no need to test it like
If (getColumnName == true)
You can write this as
If (getColumnName)
String.Format(string, method)
And String.Format method replaces items in specified string with given object, this method has two arguments first one is string and second is object.
for example
string.Format("Question number {0} is answered by {1} {2}", 11, "Adam", "Yesterday");
The out put will be
Question number 11 is answered by Adam Yesterday
As you can see {0} is replaced with 11 and {1} is replaced with Adam and {2} is replaced with Yesterday.
you can read more about this here
this is ternary operator, used for adhoc constitution of if else block.