I have come across a situation where the answer should be really straight forward, but it eludes me.
public class Note
{
#region Properties
public int Id { get; set; }
public int ClientId { get; set; }
public int CandidateId { get; set; }
public int TypeId { get; set; }
public DateTime DateCreated { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Message { get; set; }
#endregion
#region Methods
public void Save()
{
}
#endregion
}
public class History : Note
{
}
As you can see, History inherits Note. They are exactly the same, the only difference between the two is the type Id.
I have this function when getting data from the database
public static Note Parse(SqlDataReader dr)
{
int TypeId = Convert.ToInt32(dr["TypeId"]);
Note Note;
if (TypeId == 1)
Note = new Note();
else
Note = new History();
Note.Id = Convert.ToInt32(dr["Id"]);
Note.TypeId = TypeId;
if (dr["ClientId"] != DBNull.Value) Note.ClientId = Convert.ToInt32(dr["ClientId"]);
if (dr["CandidateId"] != DBNull.Value) Note.CandidateId = Convert.ToInt32(dr["CandidateId"]);
Note.DateCreated = Convert.ToDateTime(dr["DateCreated"]);
Note.UserId = Convert.ToString(dr["UserId"]);
Note.UserName = Convert.ToString(dr["UserName"]);
Note.Message = Convert.ToString(dr["Message"]);
return Note;
}
And then on my MVC page I have this:
<ol id="interview-comments">
@foreach (Note Note in Model.Notes().OfType<Note>())
{
}
</ol>
<ol id="history-comments">
@foreach (History Note in Model.Notes().OfType<History>())
{
}
</ol>
My question is simple. Is this the correct way to do it?
/r3plica
If this is the whole picture I wouldn’t use inheritance here.
You said that Note and History items had different TypeId:s.
Then I would do the following:
You could also change TypeId to an enum and “hide” some of the magic numbers
Edit:
Depending on the usage you could also implement the check for Historic notes as a property on Note.
And then the check would simple be