c# compiler error CS1526: A new expression requires (), [], or {} after type
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, EventAr开发者_如何学JAVAgs 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?
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}
The syntax should be:
Vehicle my_Car = new Vehicle();
try new Vehicle()
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.
just making further clarification and adding a reference link, the syntax for allocating new memory space using the new Operator syntax is, creating objects
Class1 obj = new Class1();
creating instances of anonymous types
var query = from cust in customers
select new { Name = cust.Name, Address = cust.PrimaryAddress };
invoke the default constructor for value types
int i = new int();
so in short and as the above answers already stated its a missing brackets that is needed for dynamic allocation of memory for an object.
精彩评论