Just double checking my understanding on reference/value semantics:
Let's say I made a List<T> values = new List<T>();
If T is a reference type, then values contains a reference to a collection of T. However, each element of this collection is then a reference to the data.
If T is a value type, then values contains a reference to a collection of T. However, each element of this collection contains the actual data.
My curiosity arose because I was trying to design a method which required an IEnumerable<T>. So if I give it a List<int> or a List<SomeObject>, it works exactly the same way, the type of T is irrelevant and everyone is happy, since it's a reference to the collection that is being provided, yes?
public sealed class Effect<T>
{
public void Apply(GameTime time, IEnumerable<T> values)
{
...
}
}
Also! This has nothing to do with boxing, right? Since List<T> has reference semantics, only a struct implementation of IEnumerable<T> would involve boxing (but this seems like a disaster waiting to happen)
Your understanding is spot-on.
My curiosity arose because I was trying to design a method which required an
IEnumerable<T>. So if I give it aList<int>or aList<SomeObject>, it works exactly the same way, the type of T is irrelevant and everyone is happy, since it's a reference to the collection that is being provided, yes?
Yes, values is a reference to the collection. This does not affect the nature of its items.
Also! This has nothing to do with boxing, right? Since
List<T>has reference semantics, only a struct implementation ofIEnumerable<T>would involve boxing (but this seems like a disaster waiting to happen)
Yes; the entire point of generic collections is to avoid boxing entirely. Neither the list itself nor its value-type items are boxed (unless the list itself is List<object>, in which case, its items are boxed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With