views:

61

answers:

2

Hi everyone, this is the first time I need to use generics and references and I'm having a difficult time of it. I know it's something obvious.

public class Program
{
    void SWAP<T>(ref T a, ref T b) { T dum = a; a = b; b = dum; }

    static void Main(string[] args)
    {
        double a = 1; double b = 2;
        double c = SWAP(a, b);

        Console.Write(a.ToString());        

        Console.Read();
    }
}

On debug "SWAP(a, b)" gives the error: The best overloaded method for 'Program.SWAP(ref double, ref double)' has some invalid arguments.

Many thanks for putting up with these types of questions, Victor

+2  A: 

Yes.. you need to pass the values in with the ref tag

edited until it compiled

public class Program {
    static void SWAP<T>( ref T a, ref T b ) {
      T dum = a;
      a = b;
      b = dum;
    }

    static void Main( string[] args ) {
      double a = 1; double b = 2;
      SWAP<double>( ref a,ref  b );

      Console.Write( a.ToString() );

      Console.Read();
    }
  }
JDMX
+1. Although `<double>` is not required.
Mehrdad Afshari
SWAP returns void, so there shouldn't be an assignment.
Joel
Thanks JDMAX, will remember that, also I made the mistake of assigning to value c, which is an error since SWAP is void.
Victor
+4  A: 

When calling a function that uses a ref value, you need to tell the compiler to take a ref. Also your SWAP doesn't return a value.

So the swap line should be

SWAP(ref a, ref b);
Joel