Search code examples
c#substringstring-length

string length and compare to int


Why does this not work ? if teaserLength for example returns 300, then it is true. if it returns for example 37, it is false.. Even though it is supposed to be reversed...

my code:

@{
     int teaserLength = item.TeaserText.Length;
}
@if (teaserLength >= 75)
{
     @item.TeaserText
}
else { 
     @item.TeaserText.Substring(1, 75)
}

And why does a TeaserText with a length of 37, give a

ArgumentOutOfRangeException
Index and length must refer to a location within the string.

on substring ?


Solution

  • The "starting" index in Substring is zero-based, and you only want the substring if the length is 75 or more:

    @if (teaserLength >= 75)
    {
         @item.TeaserText.Substring(0, 75)
    }
    else { 
         @item.TeaserText
    }
    

    or just

    @item.TeaserText.Substring(0, Math.Min(teaserLength, 75))