Question

Guys I have a string in Model.Products[i].Description. Of unknown length.

I want to have only the first 60 characters of it in a variable.

  var data = Model.Products[i].Description;
  var temp = string.Join(string.Empty,data.Take(60));

Gives me a null value exception error. What did I do wrong ?

Any help ?

Was it helpful?

Solution

Use Substring

Note: you need to check you input's length

string data = Model.Products[i].Description;
string temp = string.Empty;
if(!string.IsNullOrEmpty(data) && data.Length >= 60)
   temp = data.Substring(0,60);
else
   temp = data;

OTHER TIPS

You can use

var temp = data.Substring(0, Math.Min(data.Length, 60));

If the length of the string is less then 60 it will take the length of the string.

Wow, you actually used the method name as a tag on your question, you were so close ;)

var trim = data.Length > 60 ? 60 : data.Length;
data.Substring(0, trim);

All the answers here are ignoring the problem. data is null here. Debug your program and make sure that Model.Products[i].Description is not null.

Your current method to get the first 60 characters is a bit obtuse, but correct. The problem is you're retrieving invalid data before you even start trying to get the 60 characters.

If a null value is considered valid for you (that is, you expect it to be null sometimes) then you need to do a null check first then decide what you want to do. Do you want temp to be null or an empty string?


Here is sample code performing the check, not ideal code but designed to demonstrate the problem:

string data = Model.Products[i].Description;
string temp;
if (data == null)
{
    temp = //? what do you want "temp" to be if data is null?
}
else
{
    temp = string.Join(string.Empty,data.Take(60));
}

you are using string.Empty which is null, try:

if (data.Length>=60)
{
  temp=data.Substring(0,60);
}
var temp = data.Substring(0, 60);

NOTE: check if string (i.e. data) is null or empty and its length prior to calling Substring method.

Following is example (As stated in other valid answers)

string temp = string.Empty;
if(!string.IsNullOrEmpty(data) && data.Length >= 60)
   temp = data.Substring(0,60);
else
   temp = data;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top