Trying to keep my C# code optimized, I found that if I have a list of structure elements, each insertion would be a full copy - something that I would like to avoid.
In C++ I would simply keep a list of pointers and so I was wondering if I can do the same using C#, maybe by having the list as a list of references to the structure. Unfortunately the structure cannot be turned into a class as it is part of the XNA library (Vector3, Matrix, etc...) In any case - how would the format and usage look like if it's possible?
Thanks.
No, basically. Options:
As an example of the last;
if(arr[idx].X == 20) SomeMethod(ref arr[idx]);
Both the .X, and any usage within SomeMethod, are accessing the value directly in the array, not a copy. This is only possible with vectors (arrays), not lists.
One reason a list of refs to structs isn't possible: it would allow you I store, in the list, the address of a variable on the stack; the array usually outlives the variable on the stack, so that would be ludicrously unsafe
You can't create storeable references to structures in C#, but you could create a reference type wrapper for your value type. That said, the overhead associated with copying the memory is not going to be high for a small structure. Has your profiling shown that this is a problem?
Below is an example of a value type wrapped in a reference type. Note that this only works if all access to a particular value is through the wrapping reference type. This violates standard rules of insulation (because of the public field), but this is a bit of a special case.
public sealed class Reference<T>
where T: struct
{
public T Value;
public Reference(T value)
{
Value = value;
}
}
Another thing worth noting is that the Reference wrapper itself can take on the value null, though its contents are non-nullable. You can also add implicit or explicit conversion operators to make this more transparent, if you wish.
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