I have a class that is mostly a wrapper for a big array and some associated housekeeping. I have a function that takes a ref parameter. When I pass an instance of the class into the function, I want the array to get sent.
I considered explicit casts. Let's say I have some function that has a byte[] ref parameter.
public void SomeFunction(ref byte[] someBytes);
And that I have some class with an overloaded explicit cast.
class SomeClass
{
byte[] someBytes;
public static explicit operator byte[](SomeClass someInstance)
{
return someInstance.someBytes;
}
}
Now I want to call the function with the class as a parameter
SomeClass someInstance = new SomeClass();
SomeFunction(ref (byte[]) someInstance);
The compiler complains "a ref or out argument must be an assignable variable". I'm not sure if I'm just failing to massage the compiler properly or if you really just can't do that.
I considered a Property or function return value, but you can't pass those by ref (and after educating myself I see why...)
I'd prefer not to make the array a public field, but that does satisfy the compiler. I suppose I could just create a local variable to reference the array with, but that's an extra line of code before and after each function call...
EDIT: it might be worth noting that SomeFunction was written by a third party and I don't have access to change it. Worse, I don't think their parameter actually needs to be ref...
A cast is not an assignable variable; you're passing a return value from your explicit cast operator.
You can create a variable holding the properly cast value before passing it as a ref:
SomeClass someInstance = new SomeClass();
byte[] someBytes = (byte[])someInstance;
SomeFunction(ref someBytes);
Note that it is now the someBytes
variable which may be reassigned. You will have to take action to reassign someInstance.someBytes
in some way after the call to SomeFunction
if you want the internal value of someInstance
to be reassigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With