Reputation: 1247
I have a library that I'm trying to port to c# from c++. The library provides a class that's supposed to be a drop-in replacement for numeric types so that it can be used without substantially rewriting code. This is fairly trivial to do in c++ but I'm stuck on the lack of assignment operator overloading in c#. I want to have a class or struct that's something like:
public struct Number<T>
{
private T value;
private int importantInteger;
public Number(T initialValue, int initialInteger = 0)
{
value = initialValue;
importantInteger = initialInteger;
}
public static implicit operator Number<T>(T initialValue)
{
return new Number<T> (initialValue);
}
public static implicit operator T(Number<T> number)
{
return number.value;
}
public override string ToString ()
{
return value.ToString() + " " + importantInteger.ToString();
}
}
but has a persistent memory of the value of importantInteger
when it's updated. If I do:
var n = new Number<int>(23, 5);
n = 3*n;
Console.WriteLine(n.ToString());
then I can see that importantInteger
is equal to 0 because n = 3*n;
is creating a new Number<int>
object with the default value of importantInteger
. I would prefer that the existing object have only value
updated so that importantInteger
remains unchanged, but at the very least I would like it to be copied over to the new object.
Is there any way to accomplish anything remotely like this? I've read through many similar questions and I'm well aware that I can't overload the assignment operator. Is there any elegant way to get similar behavior though? Do I really need to have the user do something like n = Number<int>(3*n, n.importantInteger);
every single time they want to update it's value? This seems both inefficient and needlessly complicated/ugly for a user of the library. I'd really love to hear some viable alternatives that are idiomatic and more elegant.
Upvotes: 1
Views: 157
Reputation: 3290
Why not overload the mathematical operators as well?
public static Number<T> operator*(Number<T> value, Number<T> otherValue)
{
//Do your operation on otherValue here so that it is what you want
return otherValue;
}
I am not exactly sure how your importantInteger would need to be calculated here, but if you have also created an implicit cast operator for T
to Number<T>
, this should work.
To follow up for your comment. Even though you can't use arithmatic operators on generics, you Could do something like this:
if(typeof(T) == typeof(int))
{
//cast values to ints and do the math.
}
else if(typeof(T) == typeof(double))
//do double version
and so on. A little tedious, but it will get the job done.
Upvotes: 1