Daniel
Daniel

Reputation: 11054

How do I declare "Key" fields in C# anonymous types?

In VB.NET I'm used to doing things like this when creating anonymous types (VB.NET anonymous types include the notion of Key Fields):

Dim prod1 = New With {
    Key .Name = "paperclips",
    Key .Price = 1.29,
    .OnHand = 423
}

However, I haven't been able to find any way of doing this in C#, since it appears the Key keyword is not supported.

Is there any way to indicate in C# that I only want to compare some of the fields in anonymous type when looking for equality?

Upvotes: 18

Views: 2117

Answers (2)

svick
svick

Reputation: 244767

There is nothing like that in C#. In C#, all properties of anonymous types are read-only and participate in equality comparisons.

If you want to do something like this in C#, you will need to create your own (named) type.

Upvotes: 18

Ely
Ely

Reputation: 3240

There is no Key equivalent in c#.

Upvotes: 3

Related Questions