I'm trying to use the Visitor Pattern and I have as follows:
public class EnumerableActions<T> : IEnumerableActions<T>
{
private IEnumerable<T> itemsToActOn;
public EnumerableActions ( IEnumerable<T> itemsToActOn )
{
this.itemsToActOn = itemsToActOn;
}
public void VisitAllItemsUsing ( IVisitor<T> visitor )
{
foreach (T t in itemsToActOn)
{
visitor.Visit ( t );// after this, the item is unaffected.
}
}
The visitor :
internal class TagMatchVisitor : IVisitor<Tag>
{
private readonly IList<Tag> _existingTags;
public TagMatchVisitor ( IList<Tag> existingTags )
{
_existingTags = existingTags;
}
#region Implementation of IVisitor<Tag>
public void Visit ( Tag newItem )
{
Tag foundTag = _existingTags.FirstOrDefault(tg => tg.TagName.Equals(newItem.TagName, StringComparison.OrdinalIgnoreCase));
if (foundTag != null)
newItem = foundTag; // replace the existing item with this one.
}
#endregion
}
And where I'm calling the visitor :
IList<Tag> tags = ..get the list;
tags.VisitAllItemsUsing(new TagMatchVisitor(existingTags));
So .. where am I losing the reference ? after newItem = foundTag - I expect that in the foreach in the visitor I would have the new value - obviously that's not happening.
Edit I think I found the answer - in a foreach the variable is readonly.
http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19