vblang
vblang copied to clipboard
[Proposal] Create new objects from anonymous types
I suggest this general solution to the issue in #576:
Suppose we have this anonymous type:
Dim a = New With {.x = 1, .y = 2}
I suggest to allow reusing it like this:
Dim b = New TypeOf(a) With {.x = 3, .y = 4}
And in a short form, using a virtual constructor:
Dim c = New TypeOf(a)(3, 4)
VB can supstitute TypeOf(a)
with the actual temp type used for the anonymous type, and convert the constructor to filed assignment statements, in the same order they defined in the type.
Seems to found the answer, so, closing this.
I re-opn this after the discussion in #576. I find it useful to minimize code where the signature of the anonymous type contains many fields (some of them are keys) and needs some implicit type casting. So, I want to be able to write:
Dim a = New With {key .x = 1m, key .y = 2d, .z = 3}
Dim b as TypeOf a = new {6, 10, 12}
' or shorter:
Dim c as TypeOf a = (6, 10, 12)
This way, we don't need to repeat declaring the same anonymous type signature over and over.
If you keep needing the same anonymous type, that's a sign that you should just make it a full fledged type.
Not necessary. Using the same type many times in just one local function, makes it wasteful to crate a full type for it. Especially that you need many of such types in the project, one or more for each local function. I am facing these situations around LinQ results, that I want to append some values to, or return them from a function (how to write such return type?). I suggested also this to let vb infer the return type from the return statement:
Function Foo() As {}
Return SomeValue
End Function
I'm with @Echo-8-ERA on this one.
makes it wasteful to crate a full type for it.
I would argue that it's just lazy to not create a full type for it.
Although I could see the usefulness of including in a refactoring tool, an "extract anonymous type to named type" action.
Note: we considered this for c# and rejected it
@CyrusNajmabadi A link for the discussion will be helpful. Thanks.
CodeRush by DevExpress already has this as a refactoring, and I'm sure ReSharper must have it too.
The CodeRush one includes implementing IEquatable
https://docs.devexpress.com/CodeRushForRoslyn/400838/refactoring-assistance/name-anonymous-type
CodeRush by DevExpress already has this as a refactoring, and I'm sure ReSharper must have it too.
I also wrote it for Vb and C# as part of Roslyn. So you get it in VS out of hte box as well :D