Nic Foster
Nic Foster

Reputation: 2894

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?

Upvotes: 5

Views: 2910

Answers (3)

S2S2
S2S2

Reputation: 8502

If you want to check for ReadOnly fields, Use the IsInitOnly property on the FieldInfo class

http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isinitonly.aspx

//Get the Type and FieldInfo.
Type myType = typeof(myReadOnlyfield);
FieldInfo myFieldInfo = myType.GetField("ReadOnlyfield",
    BindingFlags.Public | BindingFlags.Instance);

//Check if the field is read only
bool readOnly = myFieldInfo.IsInitOnly;

Upvotes: 5

ColinE
ColinE

Reputation: 70122

Jon Skeet is right (of course), there is no such thing as a read-only object in C#. However, some framework, such as WPF have their own concept of read-only objects. WPF has freezables, objects which can be made immutable at runtime, you can check whether a freezable is frozen via IsFrozen.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500075

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.

Upvotes: 5

Related Questions