I have a dictionary with this definition Dictionary<string, object>. This dictionary gets populated with data from a form submitted to the web server.
Form fields not submitted gets what looks like an empty string set in the dictionary. E.g. if the form field MyFormField is not set, myDictionary["MyFormField"] returns "".
Lets say I get one one the values with what looks like an empty string from the dictionary like this:
var formFieldValue = formValues[formFieldName]; // Populates the formFieldValue variable with the value ""
Now, in the Immediate Window in Visual Studio, I run the following operations on the variable:
submittedFormFieldValue // => "" (just printing the value)
formFieldValue.GetType() == typeof(string) // => true
string.IsNullOrWhiteSpace(formFieldValue) // => error CS1503: Argument 1: cannot convert from 'object' to 'string'
formFieldValue.GetType() // => {Name = "String" FullName = "System.String"} ...
formFieldValue == string.Empty // => false
formFieldValue == "" // => false
So, first I get true when I compare types. The I get that argument 1 cannot convert from 'object' to 'string'.
In the Watch window, the type of formFieldValue is shown as object {string}, as opposed to if I write formFieldValue as string, which is shown as string.
What is this object {string} type?
At compile-time, the variable is of type object - which is why string.IsNullOrWhitespace fails to compile.
At execution-time the value of the variable is a reference to a string.
These two lines:
formFieldValue == string.Empty
formFieldValue == ""
... are comparing for reference identity because the left operand is of type object.
I strongly suspect if you use formFieldValue.Equals("") then it will return true. Likewise if you cast to a string first:
string formFieldStringValue = (string) formFieldValue;
if (formFieldStringValue == "")
{
...
}
... then it will enter the body of the if statement, because that == operator uses the overloaded ==(string, string) operator, which compares strings by text, instead of by reference identity.
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