-1
Dim objects As New List(Of Object)
With New Object
   .prop1 = "Property 1"
   .prop2 = "Property 2"
    objects.add(.instance) 'i mean instance of New Object
End With

is it possible.

I ask new question because last question has mislead information and I don't give right answer. so here code.

Bear0x3f
  • 142
  • 1
  • 16

2 Answers2

2

No it is not possible. The With statement basically creates an implicit variable. All you can do with that variable is access members and there is no member that returns a reference to the object itself.

If you want succinct code to create, populate and add an object to a list then do this:

myList.Add(New SomeType With {.SomeProperty = someValue,
                              .SomeOtherProperty = someOtherValue})

Interestingly, you can make it work the way you wanted if you create your own extension method. I was under the impression that you could not extend the Object class but either I was wrong or that has changed because I just tried in VB 2013 and it worked. You can write a method like this:

Imports System.Runtime.CompilerServices

Public Module ObjectExtensions

    <Extension>
    Public Function Self(Of T)(source As T) As T
        Return source
    End Function

End Module

and then do something like this:

With New SomeType
    .SomeProperty = someValue
    .SomeOtherProperty = someOtherValue
    myList.Add(.Self())
End With

I'm not sure that that really provides any benefit though, given the availability of the object initialiser syntax that I demonstrated first.

Hmmm... I just realised that that's not actually extending the Object class. It was my original intention to try to do so but then I realised that a generic method was better because it would then return the same type as you call it on. I did just test it with a non-generic method extending type Object and it did still worked though.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
0

You should to create your own class By example :

Public Class Car
Private _NumberCar As Integer
Public Property NumberCar() As Integer
    Get
        Return _NumberCar
    End Get
    Set(ByVal value As Integer)
        _NumberCar = value
    End Set
End Property


Private _ColorCar As Color
Public Property ColorCar() As Color
    Get
        Return _ColorCar
    End Get
    Set(ByVal value As Color)
        _ColorCar = value
    End Set
End Property


Private _OwnerName As String
Public Property OwnerName() As String
    Get
        Return _OwnerName
    End Get
    Set(ByVal value As String)
        _OwnerName = value
    End Set
End Property
End Class

and in the Class where you want to add the cars object do this :

    Dim CarList As New List(Of Car)
    Dim item As New Car
    With item
        .NumberCar = 1243
        .ColorCar = Color.Red
        .OwnerName = "Ibra"
    End With
    CarList.Add(item)

strong text

Ibra
  • 192
  • 11