Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diamond Syntax in C#

Java 7 now has this "diamond syntax" where I can do things like ArrayList<int> = new ArrayList<>();

I'm wondering if C# has a similar syntax that I can take advantage of.
For example, I have this part of a class:

class MyClass
{
    public List<double[][]> Prototypes; // each prototype is a array of array of doubles

    public MyClass()
    {
        Prototypes = new List<double[][]>; // I'd rather do List<>, in case I change the representation of a prototype later
    }
}

Does anyone know if this is possible, and if so, how I might go about using it?

like image 903
inspectorG4dget Avatar asked Jul 18 '13 18:07

inspectorG4dget


People also ask

What is diamond pattern?

What is 'diamond' pattern? A bearish diamond formation or diamond top is a technical analysis pattern that can be used to detect a reversal following an uptrend; however bullish diamond pattern or diamond bottom is used to detect a reversal following a downtrend.


1 Answers

No, there's nothing quite like the diamond syntax in C#. The closest you could come would be to have something like this:

public static class Lists
{
    public static List<T> NewList<T>(List<T> ignored)
    {
        return new List<T>();
    }
}

Then:

public MyClass()
{
    ProtoTypes = Lists.NewList(ProtoTypes);
}

That just uses normal generic type inference for methods to get T. Note that the value of the parameter is completely ignored - it's only the compile-time type which is important.

Personally I think this is pretty ugly, and I'd just use the constructor directly. If you change the type of ProtoTypes the compiler will spot the difference, and it won't take long at all to fix it up...

EDIT: Two alternatives to consider:

  • A similar method, but with an out parameter:

    public static class Lists
    {
        public static void NewList<T>(out List<T> list)
        {
            list = new List<T>();
        }
    }
    
    ...
    
    Lists.NewList(out ProtoTypes);
    
  • The same method, but as an extension method, with the name New:

    public static class Lists
    {
        public static List<T> New<T>(this List<T> list)
        {
            return new List<T>();
        }
    }
    
    ...
    
    ProtoTypes = ProtoTypes.New();
    

I prefer the first approach to either of these :)

like image 116
Jon Skeet Avatar answered Sep 21 '22 12:09

Jon Skeet