4

In a solution I have noticed a property that has a type enum:

Public Enum ContentType
  HTML = 1
  JSON = 2
  XML  = 3
End Enum

Public Property ContentID() As ContentType
  Get
    Return _contentID
  End Get
  Set(ByVal value As ContentType)
    _contentID= value
  End Set
End Property

Strangely these enums reflect a primary key in a table, I had an issue as a client had different primary keys and this was causing a select statement to not be entered.

Everything else seems to be working and it just got me thinking. My question is will this property throw an error if I try to set the value to be something that isn't contained in the enum? Because as I say this will definitely be happening and I have seen no errors thrown or am I missing something.

1 Answer 1

5

will this property throw an error if I try to set the value to be something that isn't contained in the enum?

It will not. Enumerations are backed by an integral type (Integer, Long etc...) and a variable will accept any valid value for its underlying type.

You can use the System.Enum.IsDefined method to check the value before trying to use it:

Returns an indication whether a constant with a specified value exists in a specified enumeration.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that what I thought. The clue was in 'enum as integer' when I hover over the type but it's good for someone with so many numbers after their username to confirm it for me!
@DavidB - Don't assume the numbers are meaningful to your situation (check where they come from - perhaps from PHP or SQL, not VB.NET...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.