Jan Mattsson Jan Mattsson - 1 year ago 81
C# Question

Can a [pure] function throw an exception?

Is it OK for a function that can throw an exception to have the [pure] attribute?

Answer Source

According to


PureAttribute attribute

Indicates that a type or method is pure, that is, it does not make any visible state changes.

So it's quite possible to throw an exception from such a method e.g.

  // factorial is a pure function: no state will be changed, 
  // just a computation 
  public static BigInteger Factorial(BigInteger value) {
    // We can't return infinity with BigInteger and that's why have to throw the exception 
    if (value < 0)
      throw new ArgumentOutOfRangeException("value", "value must be non-negative"); 


And what if I call this pure method as

  BigInteger result = Factorial(1000000000);

one of the possible outcomes is OutOfMemory exception thrown

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download