0

I try to limitate my methods so that some input arguments only allow numbers greater than zero. I thought about creating my own class, but generating an object for each method call seems to be ineffective to me. Silly example method:

public class Whatever
{
  public uint Num1 { get; }
  public double Num2 { get; }

  public Whatever (uint num1, double num2) {
    Num1 = num1;
    Num2 = num2;
  }

  public double SillyDivide() {
    var result1 = Num1 / Num2;
    var result2 = Num2 / Num1;
    return result1 + result2;
  }
}

Obviously, I try to avoid division by zero, by only allowing number higher than zero, or not equal to zero. What is the best way to implement this?

I found a Q&A here and tried to implement it, but it did not make any difference:

public class Whatever
{
  [Required]
  [Range(1, uint.MaxValue)]
  public uint Num1 { get; }

  [Required]
  [Range(double.Epsilon, double.MaxValue)]
  public double Num2 { get; }

  public Whatever (uint num1, double num2) {
    Num1 = num1;
    Num2 = num2;
  }

  public double SillyDivide() {
    var result1 = Num1 / Num2;
    var result2 = Num2 / Num1;
    return result1 + result2;
  }
}
Anno
  • 761
  • 1
  • 10
  • 22
  • 1
    Just the attributes on their own won't do anything. You need code *somewhere* that checks the value against the attributes. There are a lot of frameworks that build this in, like MVC model validation. But you didn't provide much context outside of this class. – Jonesopolis Jul 20 '21 at 15:36
  • 3
    You just need to validate your inputs. Throw an exception if a number isn't in an acceptable range for example. – DavidG Jul 20 '21 at 15:36
  • `if (num1 < 1) throw new ArgumentException("num1 must be >= 1");` Similar idea for `num2`. – Pranav Hosangadi Jul 20 '21 at 15:38
  • 1
    You can't really check whether floating point numbers are 0 or not in order to avoid a possible exception. What you should do is catch divide by 0 errors, and other potential errors from a division attempt. For all integer types you can check for 0 of course. – Bent Tranberg Jul 20 '21 at 15:39

0 Answers0