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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With