Option Strict On disallows late binding

mike picture mike · Sep 11, 2012 · Viewed 29.5k times · Source

Can someone help me fix this error?

Option Strict On disallows late binding

Here's the code that's causing the error:

Dim SF6StdData As BindingSource = New BindingSource() 
' ...
If StrComp(SF6StdData.Current("O2AreaCts").ToString, "") = 0 Then
    AreaCts(3) = 0
Else
    AreaCts(3) = Convert.ToDouble(SF6StdData.Current("O2AreaCts").ToString)
End If

I need to rewrite the code so it will not have any errors. I know I could fix this by setting Option Strict to Off in the project properties, but I really don't want to do that. Is there some other way?

Answer

Steven Doggart picture Steven Doggart · Sep 11, 2012

Late binding is not allowed when Option Strict is on. If you need to perform late binding, the only options are either to use reflection or to shut off Option Strict. The one saving grace, however, is that you don't have to shut off Option Strict for the whole project. You can leave it on for the project and then just add the line Option Strict Off at the top of any code files where you need to perform late binding. It's not a great solution, but it's better than affecting the whole project.

Also, since the Option Strict placed at the top of a file applies just to that file, it doesn't even have to apply to an entire class. If you split your class into multiple Partial Class files, then you could have Option Strict set differently for each of those files. For instance, if you put most of your class in a file with Options Strict On, and then just put one method in a Partial Class in a separate file with Option Strict Off, then only that one method would be compiled loosely. The rest of the class would be compiled using the strict rules.