0

I have an issue while using reflection to get the value of a readonly static field ViewDepartmentCompareReport from a static class .

This code works fine in most of systems that I have tried including a few in production environments but get an error

An object reference error occurred

I have created a sample fiddle of this code here https://dotnetfiddle.net/aHCoLb

The error is thrown when casting of the value Value = (BitMask)val takes place.

Please have a look at the code and point out if there is anything wrong that I am doing which could result in an object reference error when accessing the ViewDepartmentCompareReport field via reflection.

Could this error be system specific say code being executed on a x86 system behaves differently than executing on x64 system?

René Vogt
  • 43,056
  • 14
  • 77
  • 99
user581157
  • 1,327
  • 4
  • 26
  • 64

1 Answers1

1

I think you problem really lies here:

var fields = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static);
var val = fields[0].GetValue(null);
var name = fields[0].Name;

Getting a list of fields and then referencing the first one in the list and assuming that it returns a BitMask is risky. If you want to get the first field that returns a BitMask, you could do something like this:

var fields = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static);
var field = fields.First(_ => _.FieldType == typeof(BitMask));
var val = field.GetValue(null);
var name = field.Name;

You should still throw this into a try-catch block in case the type does not have a field with BitMask type, but this should at least give you an idea of how you can move forward.

Hope that helps.

MichaelDotKnox
  • 1,312
  • 1
  • 14
  • 17
  • The code i have used is just for illustration . I have a loop which then casts something like for(var field in fields) { BitMask bm = (BitMask)field.GetValue(null); } The class which i am using to read value contains only one field and no other field that is class Sample which is static and one readonly field "ViewDepartmentCompareReport" – user581157 Feb 06 '17 at 14:00
  • I knew that when I posted the code, but referencing a specific index in a list is still risky because there are potential unknowns. This is especially true if you can't reproduce the problem locally. Filtering your result set down to what you know you need reduces or even removes the unknowns. – MichaelDotKnox Feb 06 '17 at 14:04