micknt
micknt

Reputation: 297

Property with validation and convertion

This might be a basic question, but I would like to know best practice. I have a public property which takes in a value as an Integer. If that value by accident would be a String, could I in my property do validation and convertion on the fly, so the output becomes an Integer, without my script failing? Or is it best to make shure to operate with the right datatype before passing it in the property?

This is my property:

Public Property Quantity() As Integer
    Get
        Return m_Quantity
    End Get
    Set(value As Integer)
        m_Quantity = value
    End Set
End Property

Best regards!

Upvotes: 0

Views: 29

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

The property cannot be a string. Either the code will not compile, or if you don't have Option Strict/Infer on (and you really should!) the runtime conversion to Integer will fail, causing an exception.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

If that value by accident would be a String,

Such accident cannot happen in a strongly typed language because the compiler will tell you that you cannot assign a string value to an integer property. Actually you could shorten your code a little by using an Auto-Implemented Property:

Property Quantity As Integer

Upvotes: 1

Related Questions