:
: >
: > -----------------------------
: > Public Structure Cls
: > Public Parm As String
: > End Structure
: >
: > Public Class [class]
: > Public Shared Sub Main
: > Dim A As New ArrayList
: > Dim c As New Cls
: >
: >
: > c.Parm = "One"
: > A.Add(c)
: > Console.WriteLine(A.Item(0).Parm)
: >
: > 'here is the offending line
: > A.Item(0).Parm = "Two"
: >
: >
: > Console.WriteLine(A.Item(0).Parm)
: > End Sub
: > End Class
: > -----------------------------
: >
: >
: > This time, you get a runtime error.
: >
: > Latebound assignment to a field of value type 'Cls' is
: > not valid when 'Cls' is the result of a latebound expression.
: >
: >
: > As I understand it, this is a limitation of the framework, not
: > VB.Net, because C# will generate a similar error.
:
:
: One thing you can do is using 'DirectCast':
:
: \\\
: DirectCast(A.Item(0), Cls).Parm = "Two"
: ///
:
: However, note that this won't work with structures, because a copy of
: the actual object will be returned, and changing a property of the
: copy doesn't make any sense.
Agreed. In this case, it gets rid of the error message but you still
can't achieve the desired effect - you need a class for this.
The problems with structures go even deeper. Consider this variation:
---------------------------------
Public Structure Struct
Public n As Integer
End Structure
Public Class Cls
Private s As New Struct
Public Property Str() As Struct
Get
Return s
End Get
Set
s = Value
End Set
End Property
End Class
Public Class [class]
Public Shared Sub Main
Dim c As New Cls
c.Str.n = 1
End Sub
End Class
---------------------------------
This generates the compiler following error:
Expression is a value and therefore cannot be
the target of an assignment.
c.Str.n = 1
~~~~~~~
You cannot access the value type "Struct" directly from the parent Cls
object. However, if Struct is declared as a class, this compiles just
fine.
This is easy enough to work around, of course - just make the following
modification (however, this does serve to illustrate how quirky
structures are):
---------------------------------
Public Class [class]
Public Shared Sub Main
Dim c As New Cls
Dim s As Struct = c.Str
s.n = 1
End Sub
End Class
---------------------------------
As long as we're on this subject, and going back to the original
question of why a class instead of a structure, there is another
consideration as well:
<modification to original code example>
\\\
Public Structure Company
Public Name As String
Public [New] As String
Public Old As String
Public ...
End Structure
..
..
..
Dim a As New ArrayList()
Dim c As New Company()
....
a.Add(c)
///
As I understand it, since the ArrayList.Add function only accepts
objects, inserting a value type (i.e.: the Structure 'Company' above)
will involve boxing and unboxing. There are expensive operations that
would offset any gains realized by using a structure in this case.
Ralf
--