Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Introducing Brevity Into C# / Java

Tags:

java

c#

oop

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:

  1. What are possible pitfalls of this approach. What edge cases could I be missing?
  2. 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.

like image 587
rick schott Avatar asked Apr 08 '09 13:04

rick schott


1 Answers

C# saves in the other end:

var listOfInts = new List<int>();
like image 124
Peter Lillevold Avatar answered Sep 18 '22 02:09

Peter Lillevold