c# compiler error CS1526: A new expression requires (), [], or {} after type
29,992
Solution 1
Use
Vehicle my_Car = new Vehicle();
To call a constructor you need ()
after the class name, just like for function calls.
One of the following is required:
()
for a constructor call. e.g.new Vehicle()
ornew Vehicle(...)
{}
as an initializer, e.g.new Vehicle { year = 2010, mileage = 10000}
[]
for arrays, e.g.new int[3]
,new int[]{1, 2, 3}
or even justnew []{1, 2, 3}
Solution 2
The syntax should be:
Vehicle my_Car = new Vehicle();
Solution 3
try new Vehicle()
Solution 4
Assuming you are working with C# 3 or later, you can also use implicit typing and do this:
var my_Car = new Vehicle();
The same IL is produced in both cases.
Author by
Alex Gordon
Check out my YouTube channel with videos on Azure development.
Updated on July 20, 2020Comments
-
Alex Gordon almost 4 years
I am following a tutorial to create a class:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Session3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Vehicle my_Car = new Vehicle; } } class Vehicle { uint mileage; byte year; } }
I am getting the mentioned error on this line:
private void button1_Click(object sender, EventArgs e) { Vehicle my_Car = new Vehicle; }
Does anyone know what I am doing wrong?