How can I limit the length of a string to 150 characters?

Viewed 39579

I tried the following:

var a = description.Substring(0, 150);

However this gives a problem if the length of description is less than 150 chars. So is there another way I can limit the length to 150 that won't give an error when string length is for example 20.

10 Answers

It will be good if your environment support you to use below method. (As @christian-cody suggested.)

[StringLength(150)]
public string MyProperty { get; set; }

You have to include the below namespace to use it.

using System.ComponentModel.DataAnnotations;

everyone seems to be overcomplicating this, all you need is simply

var a = description;
if (description.length > 150) a = description.Substring(0, 150);

sometimes you just need to think around the problem.

As of C# 8.0 we can utilize the Range operator and end up with this:

var x = description[..150];
Related