Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting static field values of a type using reflection

I've got a set of static "enumeration" classes that I'm using to hold meaningful variable names to represent meaningless code values I receive on an input file. Here's an example of one.

Public Class ReasonCodeValue
    Private Sub New()
    End Sub
    Public Shared ReadOnly ServiceNotCovered As String = "SNCV"
    Public Shared ReadOnly MemberNotEligible As String = "MNEL"
End Class

I want to write a method that will accept the type of one of these static classes and a string value and determine whether the value is one of the static field values. I know how to get the instance fields for a specific object, and I know how to get a list of static fields for a specific type; what I can't figure out is how to get the static field values without an instance. Here's what I've got so far.

Public Function IsValidValue(ByVal type As Type, ByVal value As String) As Boolean
    Dim fields = type.GetFields(BindingFlags.Public Or BindingFlags.Static)
    For Each field As FieldInfo In fields
        DoSomething()
    Next
End Function

I supposed I could make the enumeration classes non-static just so I can create an instance to pass to FieldInfo.GetValue inside my validation method. I'd rather keep my class the way it is if I can.

I see a method called GetRawConstantValue. It looks dangerous. Will that give me what I'm looking for? Any other ideas?

like image 820
John M Gant Avatar asked Jun 02 '09 14:06

John M Gant


People also ask

What is a static data field of a class?

What Does Static Field Mean? A static field is in programming languages is the declaration for a variable that will be held in common by all instances of a class. The static modifier determines the class variable as one that will be applied universally to all instances of a particular class.

What is a static data field?

A static data field is a field that applies to an entire class of objects. To access static fields, use the class name. For example, display the TYPE field of the Integer class.

Can fields be static?

Third, the Java field can be declared static . In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class.

What is static field in C#?

A static field is a class field, which means that its data is stored in one location in memory, no matter how many objects are created from its class. In fact, you can use a static field to keep track of how many objects have been created from a particular class.


1 Answers

Call

field.GetValue(Nothing)

and it'll be fine. You don't need an instance for static members.

I don't think GetRawConstantValue is what you want - I'd stick to the code above.

like image 144
Jon Skeet Avatar answered Oct 25 '22 09:10

Jon Skeet