D
D
DancingOnWater2014-09-19 11:16:39
C++ / C#
DancingOnWater, 2014-09-19 11:16:39

Is there a C# analogue of numeric_limits from C++?

Actually, subject. For example, in my C++ template function, I could write something like

template<typename T> void fun()
{
    auto x = numeric_limits<T>::max();
}

I want something similar in C#

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aush, 2014-09-19
@DancingOnWater

Numeric types in .Net have static fields MinValue and MaxValue, so your task can be solved by reflection:

public class MyNumeric<T> where T : struct, IComparable<T>, IEquatable<T>, IConvertible
{
  public static readonly T MaxValue = ReadStaticField("MaxValue");
  public static readonly T MinValue = ReadStaticField("MinValue");

  private static T ReadStaticField(string name)
  {
    FieldInfo field = typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static);
    if (field == null)
    {
      throw new InvalidOperationException("Нечисловой тип: " + typeof(T).Name);
    }
    return (T)field.GetValue(null);
  }
}

Accordingly, use:
Console.WriteLine(MyNumeric<int>.MaxValue);
Console.WriteLine(MyNumeric<float>.MinValue);

S
Sergey, 2014-09-19
Protko @Fesor

Int16.MaxValue
Int16.MinValue
Int.MaxValue
Int.MinValue
Double.Epsilon

In a word ... partially all this is, but apparently not completely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question