C# Programming > Miscellaneous

C# Access .NET Properties
by Name

C# Properties

Reading and modifying properties of .NET objects in C# is absolutely essential. So much so that there are advanced ways to read and write these properties.

Using .NET reflection we can attempt to access properties solely with their name.

Normal Properties

Properties are usually accessed with a syntax like:

myObject.Location

Some properties can only be read and others can also have values assigned to them by the programmer. This is by far the simplest way to manipulate the properties of .NET objects in C#. It is also the cleanest and most reliable way.

Reflection

However sometimes it is necessary to access .NET properties in more direct ways. For example, a program might need to modify the property of an object with the name of the property. Let's illustrate with some code. In our above example, we accessed the Location property of myObject. We can also do the same through reflection:

Type t = myObject.GetType();
PropertyInfo p = t.GetProperty("Location");
Point location = (Point)p.GetValue(myObject, null);

Of course, PropertyInfo is location under the System.Reflection namespace. Notice that the code becomes significantly more complicated and susceptible to mistakes. For example, in the first example, trying to access a property that does not exist would trigger a compiler error. On the other hand, the example with Reflection compiles just fine no matter what property we try to access. The error will come up during run-time.

For that reason, accessing properties through reflection must be done with care and only when necessary.

Sample Program

You can download a sample C# program with source code that illustrates the points above. Additionally the source code shows how to get a list of all the public properties of a control.

 

Back to C# Article List