How to cast a string as an enum in VB.Net

This would be easy in c#, but since sometimes I must delve into the dirty that is vb.net, heres how its done there as well.

Here is the enum…

Enum Materials
	Wood= 1
	Steel = 2
	Tin = 3
	Textil = 4
End Enum

And here is how I would cast a string as one of these enums. This is most useful when we don’t yet know what the string we are casting will actually be.

Dim stringMaterial As String = "Steel"

Dim material As Materials = CType([Enum].Parse(GetType(Materials), _
	stringMaterial), Materials)

' material now equals Materials.Steel

Tags: , ,

Thursday, December 17th, 2009 Tips