Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid .NET extension methods for number datatypes?

Let's say I'd like to add an extension method called IsOdd() to the number datatypes in .NET. The implementation of this, however, will be virtually the same for the datatypes like Int16, Int32, Int64, etc., except for the parameter being defined for the extension method. I really don't like this redundancy but wonder if there's no way to avoid it.

Is there a better way to handle this? Should I instead, say, implement an extension method for System.Math and create overloaded definitions for IsOdd()? In short, I'm curious if extension methods for the number datatypes should generally be avoided altogether, due to their inherent redundancy.

like image 381
Derek Avatar asked Jun 26 '12 13:06

Derek


1 Answers

You cannot create an extension method for a static class. The closest you can do, is the following:

public static bool IsOdd<T>(this T number) where T : struct

This will restrict the extension method to value types. However, you'll still get some stuff you can't deal with (e.g. DateTime for example). You'll have to throw an exception in this case.

Edit: As Mangist said in the comments, you can do the following to further constrain the method:

 public static bool IsOdd<T>(this T number) 
     where T : struct, IComparable, IComparable<T>, 
               IConvertible, IEquatable<T>, IFormattable
like image 81
GregRos Avatar answered Sep 28 '22 11:09

GregRos