Reputation: 607
/*Class definition*/
public class ConcreteClassModel : BaseModel
{
...
public bool IntersectsWith(ConcreteClassModel ccm)
{
ccm.StartDateDT = DateTime.Parse(ccm.StartDate);
ccm.EndDateDT = DateTime.Parse(ccm.EndDate);
this.StartDateDT = DateTime.Parse(this.StartDate);
this.EndDateDT = DateTime.Parse(this.EndDate);
return !(this.StartDateDT > ccm.EndDateDT || this.EndDateDT < ccm.StartDateDT);
}
}
/*Inside Controller Method*/
List<ConcreteClassModel> periods = LoadAllByParameters<ConcreteClassModel>(
ccm.CoverId, x => x.CoverId,
ccm.SectionId, x => x.SectionId);
var intersectingPeriods =
periods.Where(x => x.IntersectsWith(ccm));
StringBuilder partReply = intersectingPeriods.Aggregate(new StringBuilder(), (a, b) => a.Append(b));
********if (!partReply.ToString().IsNullOrEmpty())***************************
{
string reply =
"<div id='duplicateErrorDialog' title='Duplication Error'><span> Duplicate Period(s)</br>" +
partReply + "</span></ div >";
return Json(reply, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
The above seems to work fine and if no duplicate date periods are found the null responce will trigger my javascript to save. However is it ok to use: if (!partReply.ToString().IsNullOrEmpty()) As StringBuilder does not have its own .IsNullOrEmpty() equivalent? Every comment, question etc that I can find relates to Strings only, and cant see anything on MSDN!
Upvotes: 0
Views: 3884
Reputation: 4168
You could create a quick method to help check if your StringBuilder
object is null or empty:
private bool IsStringBuilderNullOrEmpty(StringBuilder sb) {
return sb == null || sb.Length == 0);
}
//text examples
StringBuilder test = null;
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true
StringBuilder test = new StringBuilder();
test.Append("");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true
StringBuilder test = new StringBuilder();
test.Append("hello there");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//false
Upvotes: 0
Reputation: 28825
In your case, partReply
can never be null or empty, because Enumerable.Aggregate
throws an InvalidOperationException
when there are no input elements. Your code is crashing.
In general cases, you can compare the Length
property with 0, e.g.:
if (partReply.Length > 0)
Upvotes: 2