How to set property of an object created using Reflection?

The VB.NET to C#.NET converter tool from Developer Fusion is awesome! It convert code from VB to C# or vice versa and primarily used by enthusiasts to learn the other language syntax. The tool does a great deal of work in trans-coding. However, not every thing is translated appropriately and you may have to clean up a little bit. Here is an example of issues I faced while using Reflection.

Couple of days back I wrote code in VB.NET as shown below to load an assembly, create an object and set some properties

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            'here is dynamic loading of the libraries
            Dim asm As Assembly = Assembly.LoadFile("C:\Inetpub\wwwroot\MySite\Bin\RssReader.dll")
            Dim ctrlType As Type = asm.GetType("MySite.CustomControls.RssReader")

            Dim control As Object = Activator.CreateInstance(ctrlType)
            control.FeedUrl = "http://www.google.com/news?pz=1&ned=us&hl=en&topic=m&output=rss"
            Me.Controls.Add(control)
        End If
    End Sub

When one of my C#.NET based colleague wanted to make use of my code, he used the above VB.NET to C#.NET code and got the below code.

protected void  // ERROR: Handles clauses are not supported in C#
Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack) {
        //here is dynamic loading of the libraries
        Assembly asm = Assembly.LoadFile("C:\\Inetpub\\wwwroot\\MySite\\Bin\\RssReader.dll");
        Type ctrlType = asm.GetType("MySite.CustomControls.RssReader");
        
        object control = Activator.CreateInstance(ctrlType);
        control.FeedUrl = "http://www.google.com/news?pz=1&ned=us&hl=en&topic=m&output=rss";
        this.Controls.Add(control);
    }
}

The tool did a great job in conversion process, however, we cracked our head to fix the error

Error	1	'System.Web.UI.Control' does not contain a definition for 'FeedUrl' and no extension method 'FeedUrl' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?)	C:\Inetpub\wwwroot\MySite\Default2.aspx.cs	22	25	http://localhost/MySite/

leading to line of code

 control.FeedUrl = "http://www.google.com/news?pz=1&ned=us&hl=en&topic=m&output=rss";

The same piece of code did work in VB.NET but in C#.NET didn’t work until we modified the code as show below

ctrlType.GetProperty("FeedUrl").SetValue(control, @"http://www.google.com/news?pz=1&ned=us&hl=en&topic=m&output=rss", null);

My intention in this post is not to criticize the converter tool, but to cover ‘How to set property of an object created using Reflection?’ in both C#.NET and VB.NET

Leave a Reply

Your email address will not be published. Required fields are marked *