Check if value is 0 with extension method

  • A+
Category:Languages

I have an extension method which looks like

public static T ThrowIfObjectIsNull<T>(this T argument) where T : class {   if (argument == null)       throw new ArgumentNullException(nameof(argument));     return argument; } 

This basically check if the object that's being passed isn't null. What I am trying to do is create another extension method where the int value which is being passed in isn't 0. So I have gone ahead and created:

public static T ThrowIfZero<T>(this T argument) where T : struct {    if (argument == 0)      throw new ArgumentOutOfRangeException("some error here");     return argument; } 

Of course the above does not compile suggesting the error:

Error CS0019 Operator '==' cannot be applied to operands of type 'T' and 'int'

Can someone point me to the right direction on how I would check if the argument value isn't 0.


You could simply use Equals:

public static T ThrowIfZero<T>(this T argument) where T : struct {     if (argument.Equals(0))         throw new ArgumentOutOfRangeException("some error here");      return argument; } 

But that will not really work well if the argument if for example a decimal 0.0m which is not equal to the integer 0 as Peter has commented correctly.

So if you want a version that works for any number you could use this approach:

public static T ThrowIfZero<T>(this T argument) where T : struct {     bool isZero = Decimal.Compare(0.0m, Convert.ToDecimal(argument)) == 0;     if (isZero)         throw new ArgumentOutOfRangeException("some error here");      return argument; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: