-3

why do we have to put ' () ' when we want to define a new or array but we don't have to put it when we set predefined values ?? this problem is for c#, and its ok in VB.NET here is an example:

C#

class Program
{
    static void Main(string[] args)
    {
        MyClass w = new MyClass();
        MyClass w = new MyClass;//this line contain an error
        MyClass e = new MyClass() { ss = "" };
        MyClass g = new MyClass { ss = "" };
    }
}
class MyClass
{
    public string ss;
}

VB.NET

Sub Main()
    Dim a As my_class = New my_class()
    Dim v As my_class = New my_class
    Dim b As my_class = New my_class() With {.ss = ""}
    Dim n As my_class = New my_class With {.ss = ""}
End Sub
Class my_class
    Public ss As String
End Class
lordkian
  • 95
  • 7
  • 2
    Because C# is not VB.Net... Not really clear what kind of answer you are looking for. – Alexei Levenkov Jan 30 '16 at 07:22
  • 1
    `vb.net` was designed with compatibility to `VB6` language. `VB6` specifiacation has difference of execution depended on when method called with parenthesis or not. `C#` doesn't have that – Fabio Jan 30 '16 at 07:22
  • 1
    this is not a problem. this is how you should write code in c#. – M.kazem Akhgary Jan 30 '16 at 07:23
  • 1
    It's because of the spec for C#. I think it was a mistake to allow `new MyClass { ss = "" }`, but it's there now and we have to suck eggs. Nothing to see here. Move on. – Enigmativity Jan 30 '16 at 07:31
  • They could very easily have written the compiler to accept syntax without the (). But a compiler performs *two* important duties. Generating code is the obvious one, providing good diagnostics when you make a mistake is the much more important one. Did you *really* mean to use the default constructor or did you just forget to provide initialization arguments? The "you forgot" error message must be very different from the "you can't do that" error message to give proper guidance. – Hans Passant Jan 30 '16 at 08:44

1 Answers1

2

The specification says:

An object creation expression can omit the constructor argument list and enclosing parentheses provided it includes an object or collection initializer. Omitting the constructor argument list and enclosing parentheses is equivalent to specifying an empty argument list.

This is consistent with the array initializers:

int[] t = new[] { 1, 2, 3, 4 }; 

Very interesting answer is here: Why are C# 3.0 object initializer constructor parentheses optional?

Community
  • 1
  • 1
romanoza
  • 4,775
  • 3
  • 27
  • 44