Dale Fraser
Dale Fraser

Reputation: 4758

Ternary Operator String Length error

Whats wrong with this

ViewBag.description.Length > 160 ? 
    ViewBag.description.Substring(0, 160) : 
    ViewBag.description;

gets this error

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: Operator '>' cannot be applied to operands of type 'string' and 'int'

but its not a string, because im doing the check on length?

Upvotes: 4

Views: 1408

Answers (3)

aevitas
aevitas

Reputation: 3833

The type of exception you are seeing is described on MSDN as:

Represents an error that occurs when a dynamic bind in the C# runtime binder is processed.

Which indicates that one of your fields is dynamic. The exception details specify the Length > 160 part of your code is causing trouble, and that one of the operands is a string while the other is an int.

Now here's the fun part about dynamic typing; consider I have the following code:

dynamic d = 1;
int e = 1;

var length1 = d.Length;
var length2 = e.Length;

Where both e and d hold the same value, but they aren't of the same type. length1 will compile just fine, and I won't ever figure out that d has no Length member until runtime, whereas length2 won't compile at all because int has no member named Length.

The solution would be to explicitly cast your left and right operands before performing the < operation, in this case, casting ViewBag.description to string, and calling .Length on the result.

Upvotes: 2

stackh34p
stackh34p

Reputation: 9009

Try using explicit casts. In case the description is dynamic (as it seems from your exception), you may need to cast it. If the description field is of type string, you can do this:

( ((string) ViewBag.description).Length > 160) 
    ? ViewBag.description.Substring(0, 160)
    : (string) ViewBag.description;

I'd do this to make it more readable:

var description = (string) ViewBag.description;

ViewBag.Meta = "Text " + (description.Length > 160 
    ? description.Substring(0, 160)
    : description);

Update. As per @Dale Fraser's comment I added the full assignment according to his code.

I suppose the compiler gets confused when the chunk "Text " + description.Length is encountered as it is unable to determine the latter is part of a ternary expression - perhaps it is confused by the dynamic. This could explain the compiler error you get.

The round brackets should fix this, as they will enforce higher priority of evaluation on the ternary operator. The plus operator then will know it is performing string concatenation, as the right operand will be the evaluated ternary operator (which should be a string).

Upvotes: 1

LML
LML

Reputation: 1667

Can you try this :

 ViewBag.Meta = Convert.ToInt32(ViewBag.description.Length) > 160 ? ViewBag.description.Substring(0, 160) : ViewBag.description;

Upvotes: 0

Related Questions