Search code examples
c#vb.netdatagridviewlate-bindingvb.net-to-c#

how to avoid late binding in vb.net


I have a project written in vb.net .net version is 3.5 and its worked fine with no problems, now i decided to convert it into c#. I have using more than on tool, like instantc#, vbconversion, also the extension of visual studio all of them give me the error of late binding look to the image: the left side is the vb.net code and the right side is the converted to (i.e c#)

enter image description here

also same error on another place see image: enter image description here

please help me how to solve this problem either in the vb code so the conversion will be fine or in c# code.


Solution

  • the error of late binding

    By default C# is more strict about datatyping than VB. VB can let you assign anything to an object and write code that calls methods on it if you thought they were there:

    Dim o as Object
    o = "hello"
    
    Console.Write(o.Length) 'length of string
    

    VB doesn't let you do this if Option Strict is On - it is Off by default and it's probably the number one cause of bugs in VB.NET programs. It also encourages sloppy coding habits

    C# won't let you do this* - you have to be strict and accurate all the time and if you've assigned a string to an object then you have to prove you know what's in it by doing a cast before you can use it:

    Object o;
    o = "hello";
    
    Console.Write(((string)o).Length) 'cast o to string, then get length of string
    

    It's really tedious doing that casting all the time, when it's so much easier to just declare the proper type up front:

    String o;
    o = "hello";
    
    Console.Write(o.Length) 
    

    Late binding is a feature that lets you skip being strict at compile time, and the compiler will just assume you're right and figure out for itself at runtime, what kind of thing is inside the object variable. If it's a string, then Length will work fine. If it's an integer, which doesn't have a Length you get a crash


    So, because object doesn't have a SetDataSource method; you must declare the proper type of rpt at compile time. If it's some CrystalReports ReportViewer class then you really must declare it as that

    using CrystalReports;
    ...
    ReportViewer rpt;
    if(...)
    
    rpt.SetDataSource(...);
    

    * there are ways, but I won't go into it because it's not healthy for learning