views:

74

answers:

3

Goal :

My intention to design a utility that could access any numeric values( int,double,byte...) and produce the squares.

What i did:

 delegate  void t<T> (T somevalues);
 class program
  {
      static void Main()
      {
          Console.ReadKey(true);
      }
  }

  class Utility
  {
      public static void Activities<T>(T[] SomeValues,t<T> transformer)
      {
         var qry = SomeValues.Select(p => transformer(p));  
      }

      public static T Squaring<T>(T vals)
      {
        return vals * vals;
      }
  }

Error :

  1. Try to specify explicit type argument ( in LINQ query).

  2. Operator '*' cannot be applied to operands of type 'T' and 'T' ( in Squaring( ) ).

How can i derive constraint or change the code that can access any numerics(int,double,byte,..) and produce the square.

+2  A: 

Unlike in Java .NET doesn't have a general interface like Number for all numeric types (This question has hints on the why). But looking at this question, there seems to be a way. At least with .NET 3.5.

Joey
Thanks for the links
+1  A: 

You can't. This is a common complaint about generics in .Net. There is no way at present to declare a Type constraint that linits a type to a subset of the value types that are "numeric". If you really want to go down this path, the only option is to create your own value types that are wrappers for the core CTS numeric types, and have each of these implement an empty IAmNumber interface. Then you can have your generic method declare a type constraint on that interface... but this approach forcese you to use your custom numeric types, instead of the built-in types, everywhere you want this capability, .

Charles Bretana
A: 

Operators are defined as static function for a type. Static functions are not accessible in any generic type.

Gary