Reputation: 19
This function always returns null. sString is a class with a string "Name" and string "Value" values. Don't ask why I'm not using a regular string-- it's complicated. here's my function:
static string Get_sString(string VarName, ref List<sString> VarList)
{
foreach (sString TestsString in VarList)
{
if (TestsString.Name == VarName)
{
return TestsString.Name;
}
}
return null;
}
It's supposed to return the instance with the same Name value as VarName, and it works, except for the if statement always is false. I can't figure out why. I actually have an almost identical class called sDecimal, where the only difference is the Value property is a decimal, not a string. The Get_sDecimal() works perfectly fine with that, and the only difference between Get_sDecimal() and Get_sString() are that one tests sDecimal and one tests sString. Thanks!
EDIT: Here's sString Class.
class sString
{
public string Name;
public string Value;
/// <summary>
/// String Value variables that may have the same name.
/// </summary>
/// <param name="n">Internal name of variable.</param>
/// <param name="v">Value of variable.</param>
public sString(string n, string v)
{
Name = n;
Value = v;
}
}
EDIT: Here's some output code (and output) to clear things up.
static string Get_sString(string VarName, ref List<sString> VarList)
{
foreach (sString TestsString in VarList)
{
Console.WriteLine("Looking for: " + VarName);
Console.WriteLine("Comparing with: " + TestsString.Name);
if (TestsString.Name == VarName)
{
Console.WriteLine("Match!");
return TestsString.Name;
}
}
return null;
}
Here's the output:
Looking for: Q Comparing with: Q
EDIT: I added a couple more variables to the list. Here's the new output:
Looking for: Q Comparing with: Q Looking for: Q Comparing with: Z Looking for: Q Comparing with: VariableX
Still no Match.
Upvotes: 0
Views: 233
Reputation: 4353
You should use String.Equals instead of == operator.
== operator does not always work. you can find samples in the thread Are string.Equals() and == operator really same?.
Upvotes: 1
Reputation: 241420
You do realize that you have basically re-implemented LINQ:
return VarList.FirstOrDefault(x=> x.Name == VarName);
Also your sString
class could just be a KeyValuePair<string,string>
UPDATE
Actually, you said:
It's supposed to return the instance with the same Name value as VarName
But it doesn't return an sString
instance. Instead, it returns TestsString.Name
- which is the same string you started with, but only if it's in the list. So basically, this is a complicated "contains" check.
Upvotes: 2
Reputation: 1062502
The code fundamentally works:
var list = new List<sString>
{
new sString("foo", "123"),
new sString("bar", "456")
};
var s = Get_sString("foo", ref list);
// = "foo", not null
Don't get me wrong - I'd change every line of it. But it doesn't always return null
.
Brief problem list:
ref
Dictionary<string,string>
.Value
rather than .Name
Upvotes: 6