How to return a link in C #?

I use the Vector3D structure. I am faced with a situation that if I have a property like:

 Vector3D MyVec {get; set;} 

If I call MyVec.Normalize(); , the value of MyVec does not change. I know that struct is a value type, and getter will finely copy the new instance and return it, so the Normalize() method will modify the temp object not MyVec .

  • How can I solve this situation? Vector3D not structured, and I cannot change this.
  • Is it possible to return a link to C #?

Thanks.

+4
source share
4 answers

Assign the created structure

 MyVec = MyVec.Normalize(); 

As devio noted, if the Normalize method does not return a new structure (volatile structure is evil), here is your solution:

 var myVec = MyVec; myVec.Normalize(); MyVec = myVec; 
+5
source

A reference to the structure will result in unsafe code in .Net.

Two solutions come to mind:

  • Allow manipulation of the Vector3D structure only through classes containing such structure properties.

  • Encapsulate the Vector3D structure in a separate class and pass this class through all struct methods as you require

     public class Vector3DProxy { Vector3D value; public Vector3D Value { get ... set ... } public void Normalize() { value.Normalize(); } } 
+1
source

The method can accept a reference to the type of value.

 public void Normalize(ref YourStruct pParameter) { //some code change pParameter } Normalize(ref someParameter); 

A similar operation and exit statement: the only difference is when the use of pParameter cannot be initialized (assigned).

Edit: but this can only be used if you have control over the method, otherwise just assign a value.

0
source

I think you can only solve it like this:

 MyVec = MyVec.NormalizeVector(); public static class Extension { public static Vector3D NormalizeVector(this Vector3D vec) { vec.Normalize(); return vec; } } 
0
source

All Articles