0

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.

2
  • Possible duplicate of Store a reference to an object Commented Feb 2, 2017 at 8:08
  • 2
    In C++, there is practically no difference between a class and a struct, which isn't true in C#. A mutable struct in C# is a Very Bad Idea™. Commented Feb 2, 2017 at 8:08

2 Answers 2

4

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

@Macca: Well, you could acquire a pointer to pretty much anything within an unsafe block or an unsafe method. You could pass actual pointers around, if all methods dealing with those are marked unsafe. Or cast to IntPtr to be able to pass to managed code, and essentially pass the equivalent of void*. With the added caveat that the pointer object (unless within scope) might get moved by the garbage collector at any moment. So the only safe (or, less unsafe) way to use IntPtr would to pair it with Marshal.AllocHGlobal to get a pinned part of the memory.
1

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

4 Comments

Cool. What would the type of the member variable "target"? It's not letting me declare it ref.
ref is only for parameters, not for member declarations.
@EldritchConundrum, so this answer is not applicable then?
Yes, I am sorry, I misunderstood the question. This answer is not applicable, seems like that is not possible in C# as per the answer by @Groo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.