Today I was working on a project in VB.NET, which I had to convert to C#.
The problem was that they used late binding, they knew that some properties on objects existed, but they couldn’t be deduced by the compiler since the object’s type was Object.
For Example:
Option Strict Off Imports Microsoft.VisualBasic Public Class TestClass Public Sub Test() Dim chart As Excel.ChartObject Dim workbook = chart.Parent.Parent End Sub End Class
Now ofcourse, if you compile this, it will work since Option Strict is off.
But when you set it on (or port it to C#) for that matter it won’t compile, since chart.Parent returns a type of Object. And the compiler cannot find the .Parent property on Object.
Too bad. How do we solve this?
One option is: casting:
Option Strict On Imports Microsoft.VisualBasic Public Class TestClass Public Sub Test() Dim chart As Excel.ChartObject Dim workbook As Excel.Workbook = CType(CType(chart.Parent, Excel.Worksheet).Parent, Excel.Workbook) End Sub End Class
Unfortunately sometimes there are properties you can set, but they don’t appear in your intellisense, so you can’t get/set that property.
If you are using VB.NET with Option Strict Off this is no problem, but again: with Option Strict On or in C# it IS a problem.
So I’ve come up with a solution:
(I will continue in C#):
PropertyInfo propertyInfo = GetType(Excel.Chart).GetProperty("ThePropertyYouWant"); propertyInfo.SetValue(someChart, someValue, BindingFlags.SetProperty, null, null, null);
This won’t work either, since the compiler cannot find the propertyInfo of that property, it just doesn’t exist. You will get a NullReferenceException.
The final solution is:
GetType(Excel.Chart).InvokeMember("ThePropertyYouWant", BindingFlags.SetProperty, null, someChart, new object[] { someValue });
Guess what, this works.
I spent ages on this.
Entries (RSS)