2

In Unity you have to deal with Vector2 and Vector3 values many time in your code. Both are structs, which means when you make your code modular with small functions every time you pass such values to a function argument you copy them. Yes, you copy them in the stack but still we could make less work if we could pass it's reference. Can we pass value type to a function by reference without dealing with boxing problems.

In other words, can I get a reference on a value type variable on the stack to use it later?

P.S. I am a C++ guy, that is why I as such stupid questions :)

Narek
  • 38,779
  • 79
  • 233
  • 389
  • 1
    Try using the ref keyword... https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref – Sichi Oct 02 '18 at 17:32
  • Ref: https://stackoverflow.com/a/4807391/43846 – stuartd Oct 02 '18 at 17:33
  • See https://stackoverflow.com/questions/33375590/do-c-sharp-optimizers-perform-copy-elision . Long story short, you *may* end up with slightly-less-than-optimal code, but C# is not designed to optimize on this level. If you want, you may look up key word `unsafe` and "normal" pointers, but it's not a good idea to do so "just in case". – Abstraction Oct 05 '18 at 11:34

1 Answers1

2

Yes you can pass variables by reference in C#. example:

void Foo(ref Vector3 myVec)
{
  ...
}

Vector3 vectorA = Vector3.Zero;
Foo(ref vectorA);
BlackBrain
  • 970
  • 6
  • 18
  • Any wat to pass by `ref` and compile time make sure that it will not be modified inside the function? (Like const reference arguments in C++) – Narek Oct 04 '18 at 09:50
  • @Narek No C# does not provide such functionality – BlackBrain Aug 12 '19 at 21:24
  • 2
    @Narek now in C# 7.2 this feature is added : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier – BlackBrain Dec 20 '19 at 18:17