Note that there are some explanatory texts on larger screens.

plurals
  1. POIntroducing Brevity Into C# / Java
    primarykey
    data
    text
    <h3>Background</h3> <p>Currently, if I want to create a <code>new</code> object in C# or Java, I type something similar to the following:</p> <blockquote> <p><code>List&lt;int&gt; listOfInts = new List&lt;int&gt;(); //C#</code><br /> <code>ArrayList&lt;String&gt; data = new ArrayList&lt;String&gt;(); //Java</code></p> </blockquote> <p>C# 3.0 sought to improve conciseness by implementing the following compiler trick:</p> <blockquote> <p><code>var listofInts = new List&lt;int&gt;();</code></p> </blockquote> <h3>Question</h3> <p>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 <code>null</code> reference or assigning a specific method to instantiate it), then why can't I do the following?</p> <pre><code> //default constructors with no parameters: List&lt;int&gt; listOfInts = new(); //c# ArrayList&lt;String&gt; data = new(); //Java </code></pre> <h3>Follow Up Questions:</h3> <ol> <li>What are possible pitfalls of this approach. What edge cases could I be missing?</li> <li>Would there be other ways to shorten instantiation (without using VB6-esque <code>var</code>) and still retain meaning?</li> </ol> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload