How to get MinValue / MaxValue of a specific ValueType through reflection?

I need this at runtime. I checked the use of the Reflector line and value types of type Int16, for example, it should contain

<Serializable, StructLayout(LayoutKind.Sequential), ComVisible(True)> _
Public Structure Int16
    Implements IComparable, IFormattable, IConvertible, IComparable(Of Short), IEquatable(Of Short)

Public Const MaxValue As Short = &H7FFF
Public Const MinValue As Short = -32768


End Structure

But the following code does not work

Dim dummyValue = Activator.CreateInstance(GetType(UInt16))
Dim minValue As IComparable =    DirectCast(dummyValue.GetType.GetProperty("MinValue").GetValue(dummyValue,
Nothing), IComparable)

any idea how to solve?

EDIT : for example only, I used GetType (UInt16) directly , but in real code this part is replaced by an unknown-at-design-time instance. Type NET

+3
source share
3 answers

Use GetType.GetField("MinValue"). Constants are considered fields

+5
source

Thanks to Hanin, who answered long before me. Here is a sample code with his answer.

(17) . MinValue , , :

FieldInfo fi;
object objInt = 17;

if((fi = objInt.GetType().GetField("MinValue")) != null)
{
   objInt = fi.GetValue(null);
}
+1

This is not a property, this is a constant ...

Any reason you can't just call ?: Integer.MaxValue Integer.MinValue

0
source

Source: https://habr.com/ru/post/1739328/