Squaring a number is a rather common task in programming, but if you want to square an integer.
Easy you think!
Int MySquare = AnInt *.AnInt;
This will happily overflow without giving any exception if AnInt is bigger than 46340, unless you put your code in a checked block. Now we all do that all the time, don’t we.
No problem, we still have the Math class: Int MySquare = (int)Math.Pow(AnInt, 2); This expression never generates an overflow, but in case of it, returns int.MinValue. OK, that’s fine. Now try to use that in some math formula with lots of squares and your code looks ugly.
You could also write your own square method if you wanted to in your own utility class, but that would even be uglier than the Math class solution.
When you need other behavior from a type, you can derive from it and add some or override some of its methods. Now an int is a struct and a string is a sealed class, so you cannot do such things. But here, the designers of C#, came up with a most wonderful feature: extensions.
Used with care they can do lots of things you thought were never possible.
You have to define them as static methods in a static class and the first parameter (the type that is extended) is marked with the keyword “this”. You just have to include this file in your project and use a using clause in your program. Even intellisence will know about these extensions!
Here is my extensions file and some code samples. Enjoy.