How to use Enum from another Class in VB.NET?

What is the proper way to use my Enum values from a different class?

Public Class MainClass Private Sub asd() ' does not work: AnotherClass.WriteSomething(VAL_LIST.VAL_1, DateTime.Now.ToString) End Sub
End Class
Public Class AnotherClass Enum VAL_LIST VAL_1 VAL_2 VAL_3 End Enum Public Sub WriteSomething(ByVal myVal As VAL_LIST, ByVal myString As String) Dim _string As String = "Today is " & myString End Sub
End Class

It says << 'VAL_LIST' is not declared. It may be inaccessible due to its protection level.' is not declared. It may be inaccessible due to its protection level. >>

0

2 Answers

You need to provide an access modifier for your enum. Be default (if left off), it's private.

Public Class AnotherClass 'NOTE enum now has an access modifier. Public Enum VAL_LIST VAL_1 VAL_2 VAL_3 End Enum '...
End Class

NOTE: you should always use access modifiers to avoid confusion and reduce errors.

ADDITIONAL NOTE: Though superfluous to this topic, I would also suggest you read up on proper naming conventions, specifically -- in your case -- with regard to enums. You should name your enums and their values using Pascal Case, e.g. ValList. Furthermore, I would choose more descriptive names. VAL_LIST doesn't really indicate what it's for, and certainly VAL_1 etc. don't indicate what they are for either.

6

There is a default scope of objects in a class which is independent of the scope of the class itself.

By default Structures and Enums are Private and Variables are Public.

Best practise is to specify the Public/Private scope explicitly so you can do something like this:

Public Class AnotherClass Public Enum VAL_LIST VAL_1 VAL_2 VAL_3 End Enum
End Class

You have to now reference the Enum via the class Name:

AnotherClass.VAL_LIST.VAL_1

Although in your example WriteSomething is an instance member so you need to do the following:

Dim ac As New AnotherClass
ac.WriteSomething(AnotherClass.VAL_LIST.VAL_1, DateTime.Now.ToString)

Also please rename your Enum to something more meaningful and don't use underscores to follow best practise.

Full working example:

Public Class MainClass Private Sub Foo() Dim ac As New AnotherClass ac.WriteSomething(AnotherClass.ValueList.Value1, DateTime.Now.ToString) End Sub
End Class
Public Class AnotherClass Public Enum ValueList Value1 Value2 Value3 End Enum Public Sub WriteSomething(ByVal myVal As ValueList, ByVal myString As String) Dim _string As String = "Today is " & myString End Sub
End Class
7

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like