Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a class property has a public set (.NET)?

I have this:

public string Log
        {
            get { return log; }
            protected set
            {
                if (log != value)
                {
                    MarkModified(PropertyNames.Log, log);
                    log = value;
                }
            }

        }

And my utility class for databinding does this:

PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty);

if (!pi.CanWrite)
                SetReadOnlyCharacteristics(boundEditor);

But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists.

How can I determine if there's a public set, not just any set?

like image 886
Josh Kodroff Avatar asked Oct 09 '08 15:10

Josh Kodroff


People also ask

How do you check if property is of type is a class?

If you retrieve the value of a type's Attributes property and use the TypeAttributes. ClassSemanticsMask value to determine whether a type is a class instead of a value type, you must also call the IsValueType property. The example for the TypeAttributes enumeration contains additional information as well as anexample.

How do I find property type?

To determine the type of a particular property, do the following: Get a Type object that represents the type (the class or structure) that contains the property. If you are working with an object (an instance of a type), you can call its GetType method.

How do I find information on a property?

Typically, a deed search will start with your county clerk, recorder, auditor, or state registry of deeds; these offices might allow you to search online, but for the most complete history, you should visit the office in person and request any physical records available.

How does reflection set property value?

To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.


3 Answers

You need to use the BindingFlags. Something like

PropertyInfo property = type.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
like image 196
Darren Kopp Avatar answered Oct 28 '22 20:10

Darren Kopp


An alternative to the suggested changes to ReflectionHelper in other answers is to call pi.GetSetMethod(false) and see if the result is null.

like image 31
Jon Skeet Avatar answered Oct 28 '22 19:10

Jon Skeet


Call GetSetMethod on PropertyInfo, obtain MethodInfo and examine its properties, like IsPublic.

like image 1
Ilya Ryzhenkov Avatar answered Oct 28 '22 19:10

Ilya Ryzhenkov