Exercise 2: Design a StackOverflow PostDesign a class called Post.
This class models a StackOverflow post. It should have properties for title, description and the date/time it was created. We should be able to up-vote or down-vote a post. We should also be able to see the current vote value. In the main method, create a post, up-vote and down-vote it a few times and then display the the current vote value. In this exercise, you will learn that a StackOverflow post should provide methods for up-voting and down-voting. You should not give the ability to set the Vote property from the outside, because otherwise, you may accidentally change the votes of a class to 0 or to a random number. And this is how we create bugs in our programs. The class should always protect its state and hide its implementation detail.
solution I prepared
Post class
using System;
namespace Classes_Exercise_Mosh
{
public class Post
{
public string _title { get; set; }
public string _description { get; set; }
public DateTime _createdDate { get; set; }
public int _upVote { get; private set; } = 0;
public int _downVote { get; private set; } = 0;
public Post(string Title,string Description)
{
_title = Title;
_description = Description;
_createdDate = DateTime.Now;
}
public int UpVote()
{
_upVote++;
return _upVote;
}
public int DownVote()
{
_downVote++;
return _downVote;
}
}
}
Main Program class
using System;
using System.Threading;
namespace Classes_Exercise_Mosh
{
class Program
{
static void Main(string[] args)
{
ConsoleKeyInfo cki;
var post = new Post(“How to Throw NullReferenceException?”, “Using TryCatch Block”);
Console.WriteLine(“Post Title : {0}”,post._title);
Console.WriteLine(“Post Description: {0}”, post._description);
int choice;
do
{
cki = Console.ReadKey();
Console.WriteLine(“Enter Vote choice 1 for UpVote, 0 for DownVote:”);
choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
var votecount = post.UpVote();
Console.WriteLine("Your Upvote is:{0}", votecount);
}
if (choice == 0)
{
var downvotecount = post.DownVote();
Console.WriteLine("Your Downvote is:{0}", downvotecount);
}
} while (cki.Key != ConsoleKey.Escape);
}
}
}