none
Generic Methods - Instantiated? RRS feed

  • Question

  • Are generic methods instantiated with the same logic as generic classes? That is, a new method is created for every value-type used with a generic method call, but only one method is created for any reference type used in a generic method call?

    Thanks!

    Monday, January 28, 2019 7:54 AM

Answers

  • Perform an experiment:

     

    static void MyFunction1<T>( T a ) where T: class

    {

       Console.WriteLine( a );

    }

     

     

    static void MyFunction2<T>( T a ) where T : struct

    {

       Console.WriteLine( a );

    }

     

    . . .

     

    static void Main( string[] args )

    {

       MyFunction1( "abc" );

       MyFunction1( new object() );

     

       MyFunction2( 1234 );

       MyFunction2( 567.89 );

    }

     

    Put a breakpoint at each Console.WriteLine. When it stops, see the Registers window from Debug menu. The EIP or RIP registers represent the current address. If you see that the value is different in case of MyFunction2<int> and MyFunction2<double>, then these functions are distinct.


    Monday, January 28, 2019 9:26 AM

All replies

  • Perform an experiment:

     

    static void MyFunction1<T>( T a ) where T: class

    {

       Console.WriteLine( a );

    }

     

     

    static void MyFunction2<T>( T a ) where T : struct

    {

       Console.WriteLine( a );

    }

     

    . . .

     

    static void Main( string[] args )

    {

       MyFunction1( "abc" );

       MyFunction1( new object() );

     

       MyFunction2( 1234 );

       MyFunction2( 567.89 );

    }

     

    Put a breakpoint at each Console.WriteLine. When it stops, see the Registers window from Debug menu. The EIP or RIP registers represent the current address. If you see that the value is different in case of MyFunction2<int> and MyFunction2<double>, then these functions are distinct.


    Monday, January 28, 2019 9:26 AM
  • Thank you! You answered my question :)
    Monday, January 28, 2019 9:40 AM