Question

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?

Was it helpful?

Solution

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.)

OTHER TIPS

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);

just do what it says

request.AddExtension(new ClaimsRequest() {

if you have the new keyword you need to run the constructor ().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top