2

As part of an exercise I am trying to define a specific behavior for a generic class when used with a specific type. More precisely, I was wondering if it is possible to define a explicit casting operator for a generic type, i.e. from list<T> to int[]

No, I know I could simply define a method that does the work, however this is not the goal of the exercise.

Assuming the generic class list<T> I was trying to define the following explicit casting method

class list<T> {
...

    public static explicit operator int[](list<T> _t) where T : System.Int32 
    {
        // code handling conversion from list<int> to int[]
    }
}

This doesn't work however. Any ideas on how to make the compiler swallow this?

jonsca
  • 10,218
  • 26
  • 54
  • 62
vbeliveau
  • 23
  • 3

1 Answers1

4

Firstly, please change the name of the class to follow .NET conventions and avoid clashing with List<T>.

With that out of the way, you basically can't do what you're trying to do. You can define a conversion which is valid for all T, and then take different action for different cases. So you could write:

public static explicit operator T[](CustomList<T> input)

and then treat this differently if T is int. It wouldn't be nice to do the last part, but you could do it if you really wanted.

The members available on a particular generic type are the same whatever the type arguments (within the constraints declared at the point of type parameter declaration) - otherwise it's not really generic.

As an alternative, you could define an extension method in a top-level static non-generic type elsewhere:

public static int[] ToInt32Array(this CustomList<int> input)
{
    ...
}

That would allow you to write:

CustomList<int> list = new CustomList<int>();
int[] array = list.ToInt32Array();

Personally I'd find that clearer than an explicit conversion operator anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you for the answer. I was only fooling around trying to force the explicit casting and see if it was possible. It is obviously not the best solution. However you came up with an elegant solution. And thank you for pointing out best practices ;) – vbeliveau Oct 07 '12 at 08:42
  • Skeet, so basically the same is true for [what I am trying to do here](http://stackoverflow.com/questions/31771628/getting-the-dbcontext-dbsets-using-reflection-and-casting-to-proper-generic-type) ? Not possible ? – Veverke Aug 04 '15 at 13:28
  • @Veverke: It's not entirely clear what you're trying to do, but it doesn't look like that's feasible... – Jon Skeet Aug 04 '15 at 13:29
  • Thanks. I am most of the time trying to break things... :-) I just wanted to get the proper DbSets generic types at compile time, while I will, indeed, only know each of them at run time... making it contradictory. – Veverke Aug 04 '15 at 13:38