user588477
user588477

Reputation: 165

How to return a reference in C#?

I'm using Vector3D structure. I encounter a situation that if I have a property like:

Vector3D MyVec {get; set;}

If I call MyVec.Normalize(); the MyVec value is not modified. I know struct is value type and the getter will shallow copy a new instance and return it, so the Normalize() method will modified the temp object not MyVec itself.

  1. How can I solve this situation? Vector3D is struct not class and I cannot modify this.
  2. Can I return the reference in C#?

Thanks.

Upvotes: 4

Views: 1068

Answers (4)

Guillaume
Guillaume

Reputation: 13138

Assign the created struct

MyVec = MyVec.Normalize();

As devio pointed out, if the Normalize method doesn't return a new struct (mutable struct is evil), here is your solution :

var myVec = MyVec;
myVec.Normalize();
MyVec = myVec;

Upvotes: 5

Mert Susur
Mert Susur

Reputation: 583

I think you only may solve this like this;

MyVec = MyVec.NormalizeVector();


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

Upvotes: 0

devio
devio

Reputation: 37215

A ref to a struct would result in unsafe code in .Net.

Two solutions come to mind:

  • Allow manipulation of the Vector3D struct only via the classes containing such struct properties.

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

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

Upvotes: 1

VikciaR
VikciaR

Reputation: 3412

Method can accept reference to value type.

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

Normalize(ref someParameter);

Similar works and out operator: only difference, when use out pParameter can be not initialized(assigned).

Edit: But it's usable only if you have control to method, else simple assign value.

Upvotes: 0

Related Questions