Ok, we have the class Ticket that contains a property:
List<TaskComment> Comments;
I have it set up with a back property so that I can do some validation:
private List<TaskComment> _comments;
public List<TaskComment> Comment
{
get
{ //stuff }
internal set
{ //stuff }
}
Despite setting the set to internal, the Add() method is still exposed outside of the assembly. But regardless, what I want to do is set the ticketId property of a comment object as it is being added to the collection. For example:
var ticket = new TaskTicket();
var comment = new TaskComment { //initializers }
ticket.Comments.Add(comment);
--inside the ticket:
public List<TaskComment> Comments
{
get{ //stuff }
set
{
((TaskComment)value).TicketId = this._ticketId;
}
}
But this isn’t working. It’s telling me that it can’t cast from TaskComment to MyLibrary.TaskComment. Which really doesn’t make any sense to me. But besides that, this doesn’t feel right anyway. So how exactly do I modify the incoming value/object before adding it to the class’s collection?
Expose the
Collectionas readonly:Using the previous implementation
_commentsis now exposed to the caller. To allow the client to add/remove items you’d implementAddandRemovemembers that add\remove from the internal list.Alternatively, you could implement your own
IListproviding the proper implementations for yourAddandRemovemethods.