Background
Currently, if I want to create a new
object in C# or Java, I type something similar to the following:
List<int> listOfInts = new List<int>(); //C#
ArrayList<String> data = new ArrayList<String>(); //Java
C# 3.0 sought to improve conciseness by implementing the following compiler trick:
var listofInts = new List<int>();
Question
Since the compiler already knows that I want to create a new object of a certain type (By the fact that I'm instantiating it without assigning it a null
reference or assigning a specific method to instantiate it), then why can't I do the following?
//default constructors with no parameters:
List<int> listOfInts = new(); //c#
ArrayList<String> data = new(); //Java
Follow Up Questions:
- What are possible pitfalls of this approach. What edge cases could I be missing?
- Would there be other ways to shorten instantiation (without using VB6-esque
var
) and still retain meaning?
NOTE: One of the main benefits I see in a feature like this is clarity. Let say var wasn't limited. To me it is useless, its going to get the assignment from the right, so why bother? New() to me actually shortens it an gives meaning. Its a new() whatever you declared, which to me would be clear and concise.