4
I am doing an exercise in C# and I am not able to find the error in my code, because I have already checked the resolution of the problem and I can’t find the difference in the syntax of the code that is causing the error.
I’m getting the following feedback on the console:
Process is terminating due to Stackoverflowexception.
Follow below the codes:
Program.Cs
using System;
using Course.Entities;
namespace Course
{
class Program
{
static void Main(string[] args)
{
Comment c1 = new Comment("Have a nice trip!");
Comment c2 = new Comment("Wow that's awesome!");
Post p1 = new Post(
DateTime.Parse("21/06/2018 13:05:44"),
"Travelling to New Zealand",
"I'm going to visit this wonderful country!",
12);
p1.AddComment(c1);
p1.AddComment(c2);
Comment c3 = new Comment("Good night");
Comment c4 = new Comment("May the force be with you");
Post p2 = new Post(
DateTime.Parse("28/07/2018 23:14:19"),
"Good night guys",
"See you tomorrow",
5);
p2.AddComment(c3);
p2.AddComment(c4);
Console.WriteLine(p1);
Console.WriteLine(p2);
}
}
}
Comment.Cs
namespace Course.Entities
{
class Comment
{
public string Text { get; set; }
public Comment()
{
}
public Comment(string text)
{
Text = text;
}
}
}
Post.Cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Course.Entities
{
class Post
{
public DateTime Moment { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int Likes { get; set; }
public List<Comment> Comments { get; set; } = new List<Comment>();
public Post()
{
}
public Post(DateTime moment, string title, string content, int likes)
{
Moment = moment;
Title = title;
Content = content;
Likes = likes;
}
public void AddComment(Comment comment)
{
Comments.Add(comment);
}
public void RemoveComment(Comment comment)
{
Comments.Remove(comment);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(Title);
sb.Append(Likes);
sb.Append(" Likes - ");
sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
sb.AppendLine(Content);
sb.AppendLine("Comments:");
foreach (Comment c in Comments)
{
sb.AppendLine(c.Text);
}
return ToString();
}
}
}
Wow, that lack of attention to mine. You’re right, I forgot to add the Sb object, why it was giving the error. I was analyzing your code and didn’t know this way to use => in the method. Thank you so much for the help!
– wmazoni