Why am I getting this error when creating and returning a new structure?

I get an error when compiling this code:

using System;

public struct Vector2
{
    public event EventHandler trigger;

    public float X;
    public float Y;

    public Vector2 func()
    {
        Vector2 vector;
        vector.X = 1;
        vector.Y = 2;
        return vector;  // error CS0165: Use of unassigned local variable 'vector'
    }
}

Hello!

The compiler says: "Using an unassigned local variable" vector "and points to the return value. It seems to me that Vector2 becomes a reference type (without an event member, it acts fine). What happens?

+3
source share
3 answers

In C #, you still need a "new" struct to call the constructor if you do not initialize all fields . You left the EventHandler trigger object unassigned.

Try either assigning a "trigger" or using:

Vector2 vector = new Vector2()

, , - .

MSDN:

, . , . , , .

+14

, , , : . . , , .

.

+2

, , ( ).

, IlAsm, MSIL, , initobj.

Absence is initobjexcellent if the structure Vector2contains only value types. In the end, it's just a raw memory. However, if the structure Vector2also contains a link, it must be initialized to exclude an uninitialized reference to the object.

To avoid returning a partially unified object, you need to explicitly write an event handler triggeror initialize the entire object with a new operation. However, the structure of the structure in no case becomes a reference type.

+1
source

Source: https://habr.com/ru/post/1699689/


All Articles