Reputation: 3298
This is quite strange but I m getting this error A new expression requires (), [], or {} after type
on the following line in a controller action method
int[] Numbers = { 1, 2, 3, 4, 5}; or I have also tried
var Numbers = new int[]{1,2,3,4,5};
Also tried few other ways of getting this line work but it won't.
Other than controller action methods this works perfectly fine. Any ideas about this weird behavior?
I m using VS 2013 express edition MVC version 5 and .net framework 4.5
Here is complete action method
public ActionResult Index()
{
var LstMainModel=new List<MainModel>
var ids = new int[]{1,2,3,4,5};
foreach (var id in ids)
{
LstMainModel.Add(new MainModel{Id=id,planeModel=GetPlanes()});
}
return View(LstMainModel);
}
Upvotes: 2
Views: 3158
Reputation: 8031
Your List
is wrong.
var LstMainModel = new List<MainModel>
Should be
var LstMainModel = new List<MainModel>();
Here is a working example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
var results = TestMethod();
foreach (var item in results)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.planeModel);
}
Console.ReadKey();
return 0;
}
static List<MainModel> TestMethod()
{
var LstMainModel = new List<MainModel>();
var ids = new int[] { 1, 2, 3, 4, 5 };
foreach (var id in ids)
{
LstMainModel.Add(new MainModel { Id = id, planeModel = "TestPlane" });
}
return LstMainModel;
}
}
class MainModel
{
public int Id { get; set; }
public string planeModel { get; set; }
}
}
Also you can re-write the foreach
to a LINQ Expression, which in my opinion becomes more readable in this case.
static List<MainModel> TestMethod()
{
var ids = new int[] { 1, 2, 3, 4, 5 };
return ids.Select(id => new MainModel {Id = id, planeModel = GetPlanes()}).ToList();
}
static String GetPlanes()
{
return "PlanesTest";
}
Upvotes: 6
Reputation: 1440
It should work the way you have it but if not,
try like this: (declaring size of the array)
int[] numbers = new int[5] {1, 2, 3, 4, 5};
If it still doesn't work the problem is something else
Upvotes: 0