1

I have an array of 5 objects and also 5 textboxes. I am wanting to check to see if the values in the corresponding textbox are valid for the type of object.

I have currently hard coded this, I parse out the object type and then use a tryparse statement depending on the object type.

Can I do this automatically? Can I detect the type and use a tryparse statement for that type. Maybe something like:

if objectarray(x).tryparse(textbox(x).text, nothing)

Canning

competent_tech
  • 44,465
  • 11
  • 90
  • 113
Simon Canning
  • 215
  • 3
  • 7
  • 18

1 Answers1

1

The problem with this request is that TryParse is not specified at the object level.

If you have a fixed set of data types that you are looking for, then you may be able to use extension methods to extend the Object type or you could add the test to your ObjectArray implementation.

Update

I was able to successfully implement an extension method on the Object class in C# using the following code:

public static class MyExtensions
{
    public static bool TryParse(this Object oObject, string s, out int result)
    {
        return System.Int32.TryParse(s, out result);
    }

}

and using it as:

        Object test = new object();

        int x;

        test.TryParse("1", out x);

However, when I attempted to port this to Visual Basic, I discovered that you can extend a lot of things, but not the Object data type. This SO question has more specifics: VB.NET: impossible to use Extension method on System.Object instance

So, you can extend Object in C# or, if the objects in your arrary are of a specific base type or implement a specific interface, you could extend that in order to implement this functionality.

The alternative is to add this functionality directly to your object array class, then determine which tryparse to call based on the underlying data type.

Within the objectarray class:

Public Function TryParse(wIndex As Integer, s As String) As Boolean

    Dim oObject As Object

    oObject = Me.Item(wIndex)

    Select Case oObject.GetType.Name.ToLower
        Case "int32", "system.int32"
            Dim wTestInt As Integer
            Return Int32.TryParse(s, wTestInt)

            ' Etc...

    End Select

End Function
Community
  • 1
  • 1
competent_tech
  • 44,465
  • 11
  • 90
  • 113