public class Foo{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
public Foo(Foo source) {
this.Prop1 = source.Prop1;
this.Prop2 = source.Prop2;
}
}
public class Main
{
private List<Foo> items = new List<Foo>();
public IEnumerable<Foo> GetItems() {
foreach (Foo foo in items) {
yield return new Foo(foo);
}
}
}
public class Foo{ public string Prop1 {get;set;} public string Prop2 {get;set;} public Foo(Foo source)
Share
It depends on what you call safe. If the calling objects are just going to read information from foo. Instead of:
why not just do:
If you are attempting to prevent the calling object from modifying the original foo, what you have done will work.
You could also just set foo to be immutable, and you won’t have to worry about making sure you copy all the properties correctly etc. That way you won’t have to create a new object each time you return it through the enumerator.
Post by eric lippert on immutability:
http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx
Other link on immutability:
http://codebetter.com/blogs/patricksmacchia/archive/2008/01/13/immutable-types-understand-them-and-use-them.aspx