I created a class for convenient creation of a list that consists of different types of objects with a single interface.
A list item is created by calling a class method, the result of the method is a newly created object in the list for EDIT.
While this code works, I'm not sure if it's safe to return a list item to edit properties?
If not, how can you safely return an element from the list so that you can edit it.
var builder = new ElementBuilder();
var item = builder.AddText("abc");
// Edit new reference element property, should be stored in "builder" variable
item.Bold = true;
.....
// Pass builder instance with added items to other place
// If we do something like this with added values on above
var x = builder.First() as TextElement;
Console.WriteLine(x.Text);
Console.WriteLine(x.Bold);
// Should output:
abc
true
public class ElementBuilder
{
private List<IElement> elements = new List<IElement>();;
public TextElement AddText (string text)
{
var item = new TextElement (text);
elements.Add(item);
// RETURNING to edit properties, updates of returning should affect to list item
return _elements.First(x => x == item);
}
public ImageElement AddImage (string imageUrl)
{
var item = new ImageElement (imageUrl);
elements.Add(item);
// RETURNING to edit properties, updates of returning should affect to list item
return _elements.First(x => x == item);
}
public IElement First()
{
return elements.First();
}
.....
}
CodePudding user response:
if it's safe to return a list item to edit properties?
yeah, it is safe because what code is doing is it returns the reference to newly created item:
var item = new TextElement (text);
There are really nice posts how reference types work:
In addition, it is possible to avoid iteration of the whole collection by returning item
, not using First()
method:
public IElement AddText (string text)
{
var item = new TextElement (text);
elements.Add(item);
return item;
}
Because when you Add
item into collection, then newly created item will be added at the end of list. So, First()
method will iterate the whole List<T>
to find your item. It can be seen in source code of First()
method.