Alex Gordon
Alex Gordon

Reputation: 60691

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, 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?

Upvotes: 10

Views: 37462

Answers (5)

Wesam
Wesam

Reputation: 1040

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.

Upvotes: -1

CodesInChaos
CodesInChaos

Reputation: 108790

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() or new 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 just new []{1, 2, 3}

Upvotes: 18

dplante
dplante

Reputation: 2449

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.

Upvotes: 1

Zephyr
Zephyr

Reputation: 7823

try new Vehicle()

Upvotes: 3

George Stocker
George Stocker

Reputation: 57872

The syntax should be:

Vehicle my_Car = new Vehicle();

Upvotes: 5

Related Questions