Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an anonymous type member with a simple name

When you try to compile this:

var car = new { "toyota", 5000 };

You will get the compiler error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access." because the compiler is not able to infer the name of the properties from the respective expressions. That makes total sense.

What makes me curious is that the error message implies three valid ways to declare a type member. Member assignment and member access are obvious:

// member assignment
var v = new { Amount = 108, Message = "Hello" };

// member access
var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

What would be an example of declaring with a simple name?

Googling and the related questions on SO result in examples of member assignment and member access only.

like image 814
Frank Avatar asked Oct 27 '14 15:10

Frank


People also ask

How to declare anonymous type members?

Anonymous type members must be declared with a member assignment, simple name or member access." because the compiler is not able to infer the name of the properties from the respective expressions. That makes total sense.

What is an anonymous class?

The class has no usable name, inherits directly from Object, and contains the properties you specify in declaring the object. Because the name of the data type is not specified, it is referred to as an anonymous type.

Why do I get compiler error invalid anonymous type member declarator?

You will get the compiler error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access." because the compiler is not able to infer the name of the properties from the respective expressions.

What is the purpose of an anonymous type?

The declaration initializes a new type that uses only two properties from Product. Using anonymous types causes a smaller amount of data to be returned in the query. If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.


1 Answers

As far as I know, simple name declaration is this:

var amount = 10;
var whatever = "hello";

var newType = { amount, whatever }

Which will automatically create an anonymous type equal to:

var newType = { amount = amount, whatever = whatever }
like image 118
Haney Avatar answered Nov 15 '22 16:11

Haney