Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find default property values of a control at runtime in C#

Tags:

c#

.net

I have a control ...any System.Windows.Forms.Control. say for eg. label.

I wish to find the default value for its property called "Enabled" (can be any property for that matter). How do I do it?

1) See, in this case, we have a label. The label's default value for the property "Enabled" is true.

2) Now at runtime, suppose I wish to find out what is the default value for the property "Enabled"...how do I find out?

3)To start with I have an object of my control. From that object, I can only get the current value for the property "Enabled" but not the DEFAULT value.

One possible approach to this question could be:

1)Identify the control's type at runtime. 2)Initialize it using its default constructor. 3)Find the value of the property we are interested in (It will obviously be the default value) and there..we have the default value.

But, in this case..I don't know my control before hand. All i know is , that it can be any control from System.Windows.Forms.Control . So how do I even initialize it and get its object? Is it possible?

Do you have any alternative solution/ better approach?

like image 239
Nikhil Avatar asked Jun 22 '12 13:06

Nikhil


2 Answers

This is a good opportunity to use reflection! Here's a method which should get the default value of any property for any type which has a default constructor (public, no parameters):

public static object GetDefaultPropertyValue(Type type, string propertyName)
{
        if (type.GetConstructor(new Type[] { }) == null)
            throw new Exception(type + " doesn't have a default constructor, so there is no default instance to get a default property value from.");
        var obj = Activator.CreateInstance(type);
        return type.GetProperty(propertyName).GetValue(obj, new object[] { });
}

Note that if you are doing this with a large number of controls of which there can be multiples of a single type, you may want to cache the results for each type, as reflection is somewhat slow.

like image 147
ekolis Avatar answered Nov 14 '22 22:11

ekolis


You can instanciate an (at design time) unknown object using generics.

public class DefaultValueChecker<T> where T : System.Windows.Forms.Control, new()
{
    public bool DetermineDefaultValue() {
        var control = new T();
        return control.Enabled;
    }
}
like image 39
Dennis Traub Avatar answered Nov 14 '22 22:11

Dennis Traub