4

Is it possible to take an existing type and create an anonymous type from it with additional properties? For Example (in VB)

Public Class Person
  Public Name As String
  Public Age As Integer
End Class

Dim p As New Person With {.Name = "James", .Age = 100}

Dim n = New With {.ShoeSize = 10}

What I want is the second object (n) to clone all the properties of p and then add a new property (ShoeSize).

Is this possible?

Many Thanks

James

James
  • 720
  • 9
  • 19

2 Answers2

2

There is no syntax to do that in C#. You'll have to construct the anonymous type yourself, with all the properties.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
0

If you need to do this regularly, a modification of my extensions listed here could save some typing.

That is, if they returned string.Join(", " , from p in ps select "." + p.Name + " = " + VarName + "." + p.Name), you could at least save some typing.

An example with the variables in the OP: p.AllFieldsVb("p") returns ".Name = p.Name, .Age = p.Age".

Community
  • 1
  • 1
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101