How to make an object property truly read-only?

D

Don

If you expose an object as a property in a VB.NET class, like so:


public class MyClass
private obj as NestedClass
Public Readonly Property NestedObj as OtherClass
Get
return obj
End Get
End Property
End Class


You can't modify the object directly, but you can still modify members of
the readonly property(!):

Dim myobj as MyClass
myobj.NestedObj = New NestedClass ' Doesn't work
myobj.NestedObj.Whatever = "hello" ' Works! And the changes stick!


Is there anyway to prevent this?

- Don
 
G

Gerald Hernandez

It depends on how far you want to take this.
If you truly don't want the underlying object to be modified, you can create
a new object with the appropriate values and return that. They could modify
the values of the new object, but the underlying object would remain
unchanged. This is the easy solution, but can be confusing for the caller as
your sample below would still "work", sort of.
myobj.NestedObj.Whatever = "hello"
would not generate any sort of error, but the change would be discarded
immediately as the returned object immediately goes out of scope.

Dim tmpObj as New NestedClass
tmpObj = myobj.NestedObj
tmpObj.Whatever = "hello"

No error, and tmpObj is changed to "hello", however myobj.NestedObj is
unchanged.

If you need to make it more friendly to the user, you need to deal with the
scope of the properties of the nested object.

Gerald
 
S

steve

you build scope access from the bottom up and not the other way around. this
is as it should be. readonly for the nestedobj is correct...you cannot set
myclass.nestedobj to anything. if you want to have different access at the
nestedclass property level, then that is where you should define it. right
now, that is kind of awkward since vb.net won't support different property
access combinations until vs.net 2k5 (ex., public get with a friend set).

hth,

steve


| If you expose an object as a property in a VB.NET class, like so:
|
|
| public class MyClass
| private obj as NestedClass
| Public Readonly Property NestedObj as OtherClass
| Get
| return obj
| End Get
| End Property
| End Class
|
|
| You can't modify the object directly, but you can still modify members of
| the readonly property(!):
|
| Dim myobj as MyClass
| myobj.NestedObj = New NestedClass ' Doesn't work
| myobj.NestedObj.Whatever = "hello" ' Works! And the changes stick!
|
|
| Is there anyway to prevent this?
|
| - Don
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top