Macca
Macca

Reputation: 43

In C++ it's a member variable that is a reference to a struct. What's the C# equivalent?

I'm new to C#. The following code is how I would achieve what I want in C++. I have reasons that the struct needs to be a struct (and mutable).

What would the C# equivalent of the following code be?

struct SomeStruct {
    int a;
    int b;
};

class SomeClass {
public:
    SomeStruct& target;

public:
    SomeClass(SomeStruct &t) :
        target(t)
    {
    }
};

I want to be able to use instances of SomeClass to mutate the underlying struct. I have seen this question but in my case the target is a struct.

Upvotes: 0

Views: 170

Answers (2)

vgru
vgru

Reputation: 51204

This is not possible for struct fields. You can only get a reference to a boxed struct in C# (i.e. a separately allocated struct), and this practically cancels any benefits of using a struct in the first place.

Since structs are passed around by value (e.g. copied from function parameters into local variables), passing around pointers to struct fields would mean you would easily get pointers to out-of-scope data.

C# was deliberately designed to avoid stuff like this:

// not real C# code
void SomeMethod()
{
    SomeStruct *ptr = GetStructPointer();

    // <-- what does ptr point to at this point?
}

SomeStruct* GetStructPointer()
{
    SomeStruct local;
    return &local;
}

Upvotes: 4

Andrew Sklyarevsky
Andrew Sklyarevsky

Reputation: 2135

It would be ref SomeStruct t param. See MSDN documentation for the ref C# keyword https://msdn.microsoft.com/en-us/library/14akc2c7.aspx .

Upvotes: 1

Related Questions