Lets say I have a struct with more than hundred elements with complex names. And I am passing a struct of the struct type described to a function using ref, like this:
void Foo(ref mystruct a)
{
"I want to modify members or fields of struct a, like this:
a[0] = 10;
a[100] = 11;"
}
Thanks!
Maybe you should re-examine your choice of data structure. Perhaps a dictionary would be better suited?
It's a strange request as you're expecting the order of the fields to be significant
, but I suspect you could do this through Reflection or the TypeDescriptor.I would revise my code sample below to use proper property names with constants, but if you know the property names, just call the properties directly and save yourself from the reflection overhead. Otherwise, use a dictionary with constants.
While you can use the struct LayoutKind attribute to force simple types to share memory like a "C" Union, you still cannot make an array share memory with simple types because ref types (aka garbage collected types) don't work with the attribute. The concept of C shortcuts like memset of a struct don't map to C# in any way, because C# is a safe language. In fact, that is a Good Thing. Many bugs have come from these kinds of memory addressing shortcuts.
If you want to simulate this behavior, create a class with properties that map to specific members of a backing array, but again, why do this? There are much better data structures to suit your needs in C# such as List, SortedList, Dictionary, Map, Stack, etc. that are safe.
You can do this in .NET BUT as several others have already posted: DO NOT DO IT.
Some Code
EDIT: several reasons not to do this:
the order is not guaranteed !
what happens when there are no properties ?
what happens with readonly properties ?
So again: DO NOT DO THIS!
I will probably burn in hell, but...
Obviously horrible and not recommended and only works if your fields are all ints with default layout...