Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initializers in C# cause compile-time error

When compiling some C# code, I get the error:

A new expression requires () or [] after type

My code is as follows:

request.AddExtension(new ClaimsRequest {
        Country = DemandLevel.Request,
        Email = DemandLevel.Request,
        Gender = DemandLevel.Require,
        PostalCode = DemandLevel.Require,
        TimeZone = DemandLevel.Require,
});

I am working with ASP.NET 2.0.

Can you help explain why this error occurs?

like image 598
Adeel Aslam Avatar asked Feb 23 '23 02:02

Adeel Aslam


2 Answers

You cannot use object initializers (new T { Property = value }) unless you are writing for C# 3.0 or above.

Unfortunately, for pre-C# 3.0, you'll need to do:

ClaimsRequest cr = new ClaimsRequest();
cr.Country = DemandLevel.Request;
cr.Email = DemandLevel.Request;
cr.Gender = DemandLevel.Require;
cr.PostalCode = DemandLevel.Require;
cr.TimeZone = DemandLevel.Require;
request.AddExtension(cr);

A bit more about object initializers here.

The easiest way to tell what version of C# you are using is by looking at what version of Visual Studio you are using. C# 3.0 came bundled with Visual Studio 2008.

You do have a "way out" however. Prior to .NET 4.0 but after .NET 2.0, all new language and framework features were actually just managed libraries that sat on top of version 2.0 of the CLR. This means that if you download the C# 3.0+ compiler (as part of a later framework), you can compile your code against that compiler. (This is not trivial to do in an ASP.NET environment.)

like image 114
David Pfeffer Avatar answered Feb 24 '23 16:02

David Pfeffer


Did you perhaps copy that code from another source? It looks like you are trying to use a C# 3.0 (or above) sample (with an "object initializer") in C# 2.0.

In C# 2.0 and below you need:

ClaimsRequest req = new ClaimsRequest();
req.Country = DemandLevel.Request;
req.Email = DemandLevel.Request;
req.Gender = DemandLevel.Require;
req.PostalCode = DemandLevel.Require;
req.TimeZone = DemandLevel.Require;
request.AddExtension(req);
like image 35
Marc Gravell Avatar answered Feb 24 '23 17:02

Marc Gravell