C# passing Single as reference
-
07-07-2019 - |
Question
I would like to have a method where the parameter could be Int32
or Single
:
void myMethod( ref object x )
{
//...CodeHere
}
Since C# does not allow me to pass a specialization of object when using out
or ref
, the solution I found claimed that assigning the variable to a variable of the type object
would be enough:
Single s = 1.0F;
object o = s;
myMethod( ref o );
That didn't work. According to the Microsoft documentation I looked at, o
should be a pointer to s
. The sources I looked at state that assigning non-primitive types generate a reference and not a new
instance.
Is it possible to have a method where I can pass Single
or Int32
or any other type that is a specialization of object
?
Solution
Overload the method:
void myMethod( ref int x )
{
//...
}
void myMethod(ref single x)
{
//...
}
OTHER TIPS
Unfortunately, you're out of luck. You'll be better off using two methods:
void MyMethod(ref float x)
{
//....
}
void MyMethod(ref int x)
{
//....
}
"I would like to have a method where the parameter could be Int32 or Single"
How about using a Generic method instead?
NB: In the current version of C# you can only be able to constrain the allowable types to struct not specific types such as int, float.
Instead of boxing the value in an object, you could overload the function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
}
static int test = 0;
static void MyMethod(int arg)
{
test += arg;
}
static void MyMethod(ref int arg)
{
test += arg;
}
static void MyMethod(Single arg)
{
test += Convert.ToInt32(arg);
}
static void MyMethod(ref Single arg)
{
test += Convert.ToInt32(arg);
}
}
}
What you do with the argument inside the methods is dependent on what you're trying to accomplish, of course.
I would probably use Ash's approach and go with a generic implementation along the following lines:
static void myMethod<T>(ref T value) where T : struct, IConvertible, IComparable<T>, IEquatable<T>
{
value = (T)Convert.ChangeType(value.ToSingle(CultureInfo.CurrentCulture) * 2.0, typeof(T));
}
static void Main(string[] args)
{
int data1 = 5;
myMethod(ref data1);
if (data1 != 10)
throw new InvalidOperationException();
Single data2 = 1.5f;
myMethod(ref data2);
if (data2 != 3)
throw new InvalidOperationException();
}