Saleh
Saleh

Reputation: 3032

My Swap Function Don't Work

I want to discuss my problem clearly.
I have a function to Swap value of two variable

    public static void Swap<T>(ref T first, ref T second)
    {
        T temp = first;
        first = second;
        second = temp;
    }

I have use it in my code as this:

        Swap<DateTime>(ref TarikhePayaneGozaresh, ref TarikheShorooeGhozaresh);

I have checked it many times and now I am confused. As you can see the value didn't swaped!
Update : I have write more of my code.

Upvotes: 3

Views: 324

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273199

Where exactly do you do the verification?

I notice that inside CalculateMablagheDariaftieKol() you Swap a ref with a non-ref parameter.

So outside CalculateMablagheDariaftieKol() you will not see a (complete) Swap.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062640

The swap works fine:

var TarikhePayaneGozaresh = DateTime.Parse("9/9/2010 12:00:00 AM");
var TarikheShorooeGharardad = DateTime.Parse("9/9/1991 12:00:00 AM");
Swap<DateTime>(ref TarikhePayaneGozaresh, ref TarikheShorooeGharardad);
Console.WriteLine(TarikhePayaneGozaresh); // 09/09/1991 00:00:00
Console.WriteLine(TarikheShorooeGharardad); //09/09/2010 00:00:00

I can only conclude that the problem is something outside of the code you have shown us, for example:

  • confusing which fields/properties/variables TarikheShorooeGharardad and TarikhePayaneGozaresh refer to at each point (hit "show definition" to ensure they are the same)
  • in the case of fields/properties, confusing which objects they relate to
  • anything involving mutable structs (i.e. structs with values that can change after creation)... mutable structs are evil and will always cause confusion such as changes which seem to evaporate unexpectedly
    • or doubly so if it has explicit layout (unlikely, but even more evil if abused)

Upvotes: 4

Related Questions