0

I have a simple bit of code where i check the position of my mouse and if it is not null, i snap the position to a particular place.

The problem is, i can't seem to pass the value to the method. The code looks like this:

        Vector3? T = Mouse.WorldPosition;
        if (T != null)
        {
            FindSnapPoint(ref T.Value); //property or indexer may not be passed
        }

Why is this not allowed? And what can I do to fix this problem, i don't use a return since i use this method in a lot of places and it makes it a lot more elegant if i ref the value.

Is my only option here to revert to returning a Vector3 rather than using ref?

Sir
  • 8,135
  • 17
  • 83
  • 146
  • Well that doesn't really explain what the solution is all that clearly.. other than i guess make another Vector3 ? If i make my own then i have to use `out` and that breaks all the rest of my code where i am not passing nullables. – Sir May 25 '17 at 01:15
  • Even if you did chose to use a return value, you also wouldn't be able to write `T.Value = FindSnapPoint()` since `Value` is read-only. That should make it obvious why you can't expect it to be written through a ref parameter either. – Steven May 25 '17 at 01:17
  • 1
    Short answer; indexers and properties are implemented as methods under the hood. Thus, you cannot pass a *reference* to the value, since it's actually retrieved by invoking a method. – Rob May 25 '17 at 01:18
  • So i would be better off just doing a normal return of a Vector3 ? – Sir May 25 '17 at 01:20
  • 1
    Without knowing more context: yes, it is generally advisable to avoid ref/out parameters. If you really want to keep your method as it is, you could introduce a local `Vector3` variable, initialize it with `T.Value` and pass that as argument. But remember that this won't immediately change the value of `T`. – Steven May 25 '17 at 01:23

0 Answers0