Hello :)
I'm from a C++ background and have been toying with C#, I'm attempting to return a parameter by reference, something like:
cVector3& cCamera::getPosition()
{
return mPosition;
}
Although many google searches later I haven't been able to uncover anything :(
Loading
Richard BangsPosted Jul 1, 2007, 12:53 PM
Awesome, thanks for the detailed answers :o)
AlanPosted Jul 1, 2007, 11:25 AM
It's just dawned on me that you're probably using the Vector3 structure in the XNA framework, so it is in fact a value type.
I think your best bet is to use 'out' parameters to compensate for C#'s inability to return a struct by reference.
AlanPosted Jul 1, 2007, 11:14 AM
A reference in .NET parlance is a pointer to an object on the managed heap, which is tracked by the garbage collector.
However, if Vector3 is defined as a struct, the method would just return the object 'by value' i.e. a copy would be made and so outside code wouldn't be able to modify the original object.
This difference between classes ('reference types') and structs ('value types') in C# takes some getting used after C++ where, of course, classes and structs are essentially the same thing but with different default accessibility for their members.
If you're using 'unsafe' code in C#, it is possible for a method to return a pointer to a value type but this is not usually recommended apart from unmanaged interop scenarios.
Richard BangsPosted Jul 1, 2007, 10:32 AM
Vector3& cCamera::GetPosition()
{
return mvPosition;
}
This would be useful because in this use I would want to do operations on the returned vector and not have to implement functions for each mathematical operation or using get and set accessors.
So I could do (in C++):
mCamera.Position() += vDiffPosition * fScale;
rather than in C# where I'm currently having to do:
mCamera.SetPosition( mCamera.GetPosition() + ( vDiffPosition * fScale ) );
Although, I suppose a further solution would be to make mvPosition public, but this feels bad, its nice to be able to breakpoint Position() if something strange was to occur with the camera's position.
AlanPosted Jul 1, 2007, 9:02 AM
To pass a parameter by reference in C#, use the 'ref' keyword both in the method definition and in the call.
If the parameter is initially unassigned, you can use the 'out' keyword instead. The compiler then ensures that the parameter will have been assigned to before the method ends.
Here's a very simple example:
using System;
class Program
{
static void Main()
{
int i = 3 ;
MyMethod(ref i);
Console.WriteLine("i is now {0}", i); // i now 4
int j; // unassigned
MyMethod2(out j);
Console.WriteLine("j is now {0}", j); // j now 5
Console.ReadLine();
}
static void MyMethod(ref int i)
{
i++;
}
static void MyMethod2(out int i)
{
i = 5;
}
}