Question

I have a code like this:

public static IEnumerable<IntEx> FibbonacciNumbersStr()
{
    IntEx j = 0;
    IntEx i = 1;
    for (Int64 k = 0; k < Int64.MaxValue; k++)
    {
        yield return j;
        IntEx oldi = i;
        i = i+j;
        j = oldi;
    }
}

IntEx is a custom 'int' class able to calculate gigantic numbers and write them as string in any given number base, the problem here is, when I say IntEx oldi = i, oldi will be a POINTER to i and ends up not doing its purpose, (thus making that fibonacci sequence totally wrong. Tho, if I do

public static IEnumerable<IntEx> FibbonacciNumbersStr()
{
    IntEx j = 0;
    IntEx i = 1;
    for (Int64 k = 0; k < Int64.MaxValue; k++)
    {
        yield return j;
        IntEx oldi = new IntEx(i);
        i = i+j;
        j = oldi;
    }
}

It works perfectly.

Is there any way I can get the second result using the simple = operator to reinstantiate instead of pointing to, thus imitating better the behavior of Int64 or something? I mean, the point here is I may end up wanting to distribute this code for other people to work with and they would probably end up having that 'point to instead of being a new value' problem when using IntEx class -_-

Any ideas?

Was it helpful?

Solution

There is no way to override the = behavior in C#. If IntEx is a class type then assignment will always cause the LHS to refer to the same value as the RHS.

This can be solved to a degree by inserting a struct into the equation. In struct assignment are fields are copied memberwise between the LHS and RHS. It still can't be customized but does ensure some separation of the values

OTHER TIPS

you can always create a static method to set a value.

Thus this solutions would work.

IntEx.SetValue(i);

or make the IntEx produce instances not by creating new but making a static method to it like.

IntEx.CreateInstance(i);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top