Is it possible to create constructor-extension-method ? how?

Tar picture Tar · Jan 24, 2011 · Viewed 32k times · Source

Is it possible to add a constructor extension method ? I want to add a List< T > constructor to receive specific amount of bytes out of a given partially filled buffer (without the overhead of copying only the relevant bytes and so on):

...
public static List<T>(this List<T> l, T[] a, int n)
{
    for (int i = 0; i < n; i++)
       l.Add(a[i]);
}
...

so the usage would be:

List<byte> some_list = new List<byte>(my_byte_array,number_of_bytes);

I've already added an AddRange extension method:

public static void AddRange<T>(this List<T> l, T[] a, int n)
{
   for (int i = 0; i < n; i++)
       l.Add(a[i]);
}

I want to do it as a constructor too. Is it possible ? if yes - how ?

Answer

fearofawhackplanet picture fearofawhackplanet · Jan 24, 2011

No, but if you changed your AddRange signature to return the list instance, then you could at least do

var list = new List<int>().AddRange(array, n);

which imho is probably clearer than overloading the constructor anyway.