• 0 Posts
  • 2 Comments
Joined 2 years ago
cake
Cake day: June 26th, 2023

help-circle
  • C# .NET using reflection, integer underflow, and a touch of LINQ. Should work for all integer types. (edit: also works with char values)

    // this increments i
    private static T Increment<T>(T i)
    {
        var valType = typeof(T);
        var maxField = valType.GetField("MaxValue");
        var minField = valType.GetField("MinValue");
        if (maxField != null)
        {
            T maxValue = (T)maxField.GetValue(i);
            T minValue = (T)minField.GetValue(i);
    
            var methods = valType.GetTypeInfo().DeclaredMethods;
            var subMethod = methods.Where(m => m.Name.EndsWith("op_Subtraction")).First();
                   
            T interim = (T)subMethod.Invoke(
                null,
                [i, maxValue]);
    
            return (T)subMethod.Invoke(
                null, 
                [interim, minValue]);
        }
        throw new ArgumentException("Not incrementable.");
    }