views:

47

answers:

1

We use spark to generate HTML-mails. When merging our data into the template I noticed a difference between

<if condition="Equals(#context.UserAccount.Country,'BE')">
  <p>You live in Belgium</p>
</if>
<else>
  <p>You don't live in Belgium</p>
</else>

and

<if condition="#context.UserAccount.Country == 'BE'">
  <p>You live in Belgium</p>
</if>
<else>
  <p>You don't live in Belgium</p>
</else>

When I pass in a UserAccount with country set to 'BE' the first one prints correctly 'You live in Belgium', the second one produces the incorrect result.

Can someone tell me why? Can you test on equality of strings without using Equals()?

+1  A: 

So the code you posted throws a compiler error when I try to run it. However, the error I get explains why you're seeing different behavior. The error I get his this:

    CS0252: Warning as Error: Possible unintended reference comparison; 
    to get a value comparison, cast the left hand side to type 'string'

Looking at the code that Spark generates, the error and behavior you're seeing makes a lot more sense. First piece of code generates the following comparison:

    if (Equals(Eval("context.UserAccount.Country"),"BE"))

I'm pretty sure Eval returns something of type object (regardless of what the actual type of the variable is). Then the call to Equals is probably equivalent to doing this:

    Eval("context.UserAccount.Country").Equals("BE")

which then uses the overloaded equals method on the string class (thank you polymorphism) which would return true. Where as the second case:

    if (Eval("context.UserAccount.Country") == "BE")

probably just does a reference comparison between two objects, which returns false.

If you don't use the # before context.UserAccount.Country, Spark will generate the following code (notice the lack of call to Eval):

    if (context.UserAccount.Country == "BE")

Assuming context has a UserAccount property, that has a Country property of type string then the expression should correctly evaluate to true when Country has the value of "BE".

R0MANARMY
Thank you for the information. We are using Spark to generate emails (outside of MVC-context), maybe that's why you can't compile the code.The solution you proposed did not work for me. I got an error CS0103: The name 'context' does not exist in the current context.Your answer is however correct in the fact that it is due to the EVAL-function that I get an incorrect result with the second example. If I cast the #context.UserAccount.Country explicitly to string. So this works also: if ((string)#context.UserAccount.Country) == "BE").Thanks for giving me the hint.
Jelle