Ternary Operator line length error

What's wrong with that

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

gets this error

An exception like "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" occurred in System.Core.dll, but was not processed in the user code

Additional information: The operator '>' cannot be applied to operands; enter 'string' and 'int'

but this is not a string because im doing a length check?

+4
source share
3 answers

The type of exception you see is described in MSDN as:

Represents an error that occurs during dynamic binding in the C # runtime environment. The binder is being processed.

, dynamic. , Length > 160 , - string, - int.

dynamic typing; :

dynamic d = 1;
int e = 1;

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

e d , . length1 , , d Length , length2 , int Length.

, <, , ViewBag.description .Length .

+2

. description ( ), . description string, :

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

, :

var description = (string) ViewBag.description;

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

. @Dale Fraser .

, , "Text " + description.Length, , - , . , .

, . , , ( ).

+1

Can you try this:

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

Source: https://habr.com/ru/post/1533294/


All Articles