vb.netwinformstoolstriptoolstripitem

Option Strict On disallows implicit conversions between String and Object {String}


I am trying to clean my ways as a beginner programmer by using Option Strict On. I managed to clean all errors except this one.
I am using the Tag property of a ToolStrip for some text information. Clicking on the ToolStrip, I need to remember the value of the Tag in a string and change the value of that Tag.

How can I convert the Object {String} sender.tag to a String and the String myString and an Object {String}?

Private Sub ToolStrip_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles ToolStrip.ItemClicked
    Dim myString As String = sender.tag
    sender.tag = "It is selected"
    'more code...
End Sub

Edit: see here a screenshot of the relevant part of the code:

enter image description here


Solution

  • Good that you have titled your question generically. And you need a generic answer.

    Option Strict On is a good thing. It makes harder to code but performance at runtime will increase because there will be less implicit data type conversions.

    Lets take your code ...sender As Object... and ...sender.tag.. This is a typical thing in .net. Often you see a parameter of type object, which means, any data type can be passed. Object does not have all the properties and methods defined that belong to that data type.

    For example

    Dim oTxt as object = new TextBox()
    

    oTxt will not automatically have property Text. You need to cast. When you know 100% the object type, do

    dim str as string = DirectCast(oTxt, TextBox).Text
    

    But sometimes you don't know what Type is in your object. In this case you try casting and then check for null

    dim txtBx as TextBox = TryCast(oTxt, TextBox)
    if txtBx IsNot Nothing Then str = txtBx.Text
    

    Your real problem is that you need to understand type casting. You should cast it explicitly even if you don't have Options Strinct On because when you do x = sender.tag implicitly, you really using a late binding, which is bad for performance. And this also opens doors for potential runtime errors.

    Your topics of research should be: type casting, late binding, boxing/unboxing