Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What benefit does the ImmutableObject attribute provide?

I was testing the ImmutableObjectAttribute attribute just for curiosity to see if I could gain some beneffits applying it, or if it was just for semantic decoration...

  • ImmutableObjectAttribute Class

Specifies that an object has no subproperties capable of being edited.

So I have this class:

<ImmutableObject(True)>
Public Class TestClass

    <ImmutableObject(True)>
    Public sb As StringBuilder

    Public Sub New()
        sb = New StringBuilder
    End Sub

End Class

And I've tested with this code:

    Dim obj As New TestClass

    obj.sb.Append("Hello")
    obj.sb.Append(" ")
    obj.sb.Append("World")

    MsgBox(obj.sb.ToString)

Then, after I'd applied the ImmutableObject attribute in a mutable object, I expected to see some kind of compiler warning, some sort of runtime exception, or just receive an unexpected value from the internal string of the StringBuilder, but nothing of that things happened, all seems to work as normally.

That makes me think a question whose answer seems obvious, but I need to ask it:

  • Is the ImmutableObject attribute just a decorative attribute?.

Why exists this attribute then? I cannot find any beneffit marking a class with this attribute it it not ensures that the members are really immutable, or at least what .Net understands for immutable (you know, like a String is not really immutable in .Net).

like image 406
ElektroStudios Avatar asked Dec 25 '22 10:12

ElektroStudios


1 Answers

From the ImmutableObjectAttribute Class documentation:

This attribute is typically used in the Properties window to determine whether to render an expandable object as read-only. As such, this property is used only at design time.

... so yes, this is only for decoration.

like image 181
Matthew Whited Avatar answered Jan 15 '23 19:01

Matthew Whited