Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an instance of an Object is read-only

If I have an instance of an Object, how do I check whether or not it is read only?

I've scoured through System.Type and that are plenty of IsXxxx() and GetXxxx() types of functions but no IsReadOnly(), IsWriteable(), GetReadWriteProperty(), or anything along those lines. I guess something like myObj.GetType().IsReadOnly() would've been too easy, and the Object class itself has nothing useful in it other than GetType().

When I google this question all I get are ways to use the readonly keyword.

I thought of using Reflection and GetProperty() but this is a base class that exists in a List<>, I would need the instance of this object to be a lone property in another object for me to do this I would think.

Any ideas?

like image 759
Nic Foster Avatar asked Jan 19 '12 06:01

Nic Foster


1 Answers

There's no such concept as an object being read-only. A variable can be read-only, but that's a different matter. For example:

class Foo
{
    private readonly StringBuilder readOnlyBuilder;
    private StringBuilder writableBuilder;

    public Foo()
    {
        readOnlyBuilder = new StringBuilder();
        writableBuilder = readOnlyBuilder;
    }
}

Here there's only one StringBuilder object, but two fields - one read-only and one writable.

If you're asking whether a type is immutable (e.g. string is immutable, StringBuilder isn't) that's a thornier question... there are many different kinds of immutability. See Eric Lippert's blog post on the matter for more details.

like image 99
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet