Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit or explicit conversion from T to T[]

Tags:

c#

.net

generics

Is there a way to implement a generic implicit or explicit converter for anything to an array of anything, something like this:

public static implicit operator T[](T objToConvert)
{
    return new T[] { objToConvert };
}
like image 349
Jimmy Hoffa Avatar asked Dec 08 '22 02:12

Jimmy Hoffa


2 Answers

No. The closest I can think of is an extension method:

public static T[] AsArray<T>(this T instance) 
{
    return new T[]{instance};
}

Use as:

var myArray = myInstnace.AsArray();
like image 160
driis Avatar answered Jan 04 '23 00:01

driis


Note that you can omit the type name from the array constructor, which means the syntax is fairly clean, even with a long type name:

ReallyLongAndAwkwardTypeName value;
MethodThatTakesArray(new[] {value}); 
like image 45
Dan Bryant Avatar answered Jan 04 '23 01:01

Dan Bryant