Object initializers in C # cause a compile-time error

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

The 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 explain the cause of this error?

+4
source share
3 answers

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

Unfortunately, for pre-C # 3.0 you will 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); 

Here is a bit more about object initializers.

The easiest way to tell which version of C # you are using is to see which version of Visual Studio you are using. C # 3.0 came bundled with Visual Studio 2008.

However, you have a way out. Prior to .NET 4.0, but after .NET 2.0, all of the new language and framework features were actually managed libraries that were on top of the 2.0 CLR. This means that if you download the C # 3.0+ compiler (as part of a later version), you can compile your code with this compiler. (This is not so difficult to do in ASP.NET.)

+6
source

Did you copy this code from another source? It looks like you are trying to use a C # 3.0 sample (or higher) (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); 
+4
source

just follow what he says

 request.AddExtension(new ClaimsRequest() { 

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

-2
source

Source: https://habr.com/ru/post/1386518/


All Articles