I
I
Iq512017-04-19 00:37:40
Programming
Iq51, 2017-04-19 00:37:40

Does a reference field in a C# structure affect anything?

For example:

struct MyStruct
{
    int id;
    MyClass myClass;
}

Or is it better to do without reference types in the structure?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2017-04-19
@Iq51

Do as the situation demands. There are no restrictions.
Perhaps there will be some inconvenience when saving to the database or serialization, but again it depends on the situation and there are a lot of solutions to get rid of these inconveniences.

E
Eugene, 2017-04-19
@evgshk

You need to be careful when copying them.
In your case, the myClass field stores a reference to a memory area on the heap. Copying a value type( which is what a struct refers to) just creates a new value on the stack.

var a = 0;
var b = a; //на стек помещается значение 0. Число есть число, ни на что не ссылается

In a copy of the structure, the reference field is initialized with a copy of the reference (and it leads to the same object on the heap) which is placed on the stack. In other words, you will get a superficial or shallow copy. When you change the properties of an object of a reference type in one structure, you will see the same changes in the copy field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question