Squaring an integer with extensions

ddanbe 0 Tallied Votes 376 Views Share

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.

/**********************************************************
 * 
 *    Utilities for string, bool an int types.
 * 
 *    DM 
 * 
 *    Last edit: 29/10/2013
 * 
 * *******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;


namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static bool IsEven(this Int32 intnum)
        {
            return (intnum & 1) == 0;
        }

        public static bool IsOdd(this Int32 intnum)
        {
            return (intnum & 1) != 0;
        }

        public static int Squared(this Int32 intnum)
        {
            Int32 sqr = 0;
            // Max intnum = 46340
            try
            {
                checked //needed to generate owerflow exeption
                {
                    sqr = intnum * intnum;
                }
            }
            catch (OverflowException)
            {
                sqr = Int32.MinValue;
            }
            return sqr;
        }

        public static string RoundToTenStr(this double d)
        {
            return ((Math.Round(d / 10.0)) * 10).ToString();
        }

        public static string RoundToStr(this double d)
        {
            return Math.Round(d).ToString();
        }

        public static List<T> ListMultiples<T>(this List<T> list, int multipleNr)
        {
            var result = list.GroupBy(x => x).Where(x => x.Count() > multipleNr).SelectMany(x => x).Distinct();
            return result.ToList();
        }
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
//Some code samples of the use:

            int a = 3; 
            int b = 4;
            int c = a.Squared() + b.Squared();
            Console.WriteLine("The sum of the squares of 3 and 4 is: {0}", c);
            // Also possible:
            Console.WriteLine("Also possible: 3^2 + 4^2 = {0}", 3.Squared() + 4.Squared());
castajiz_2 35 Posting Whiz

nice LINQ

ddanbe 2,724 Professional Procrastinator Featured Poster

In fact, the possibility to use extensions was added to C# to make LINQ possible. I use no queries here.

Ketsuekiame 860 Master Poster Featured Poster

I use no queries here

list.GroupBy(x => x).Where(x => x.Count() > multipleNr).SelectMany(x => x).Distinct();

That's a LINQ statement ;)

ddanbe 2,724 Professional Procrastinator Featured Poster

OOPS! Yes you are right Ketsuekiame. It was the last method I added. It was first my intention to only show the Squared method, but then I decided to drop in my whole extension file. BTW any comments on the efficiency or improvement on this query statement are more than welcome.

Ketsuekiame 860 Master Poster Featured Poster

I'm not entirely sure what your query is doing tbh, but if you want to list all the numbers for which multipleNr is the multiple for I would have done: list.Where(x => (multipleNr % x) == 0)

If you were trying to find all the numbers which are multiples of multipleNr, just switch the mod satement around.

EDIT: Your query only lists duplicate values where that value is repeated more times than multipleNr. Is that what you were trying to do?

ddanbe 2,724 Professional Procrastinator Featured Poster

Thanks for the reply. Sorry that I gave not sufficient explanation.
I'm doing this little project for a collegue at my previous work.
He has a list in Excel of 5000 and more chemical components. He wants to have a list(filter out) the same names that appear say more than 3(=multipleNr) times in the list.

Ketsuekiame 860 Master Poster Featured Poster

In that case, I suggest you call the method ListDuplicates and the variable minimumNumberOfEntries

ListMultiples is a bit confusing because it shares its name with the mathematical term :)

If you do call it minimumNumberOfEntries then you'll need to change the where clause to be >=.

The only improvement I'd make is, rather than flattening your list, simply select the key. This avoids a lot of sub-processing (you only need to select a single value instead of all of them) and completely removes the need to make a Distinct filter. Updated query below :)

list.GroupBy(x => x).Where(x => x.Count() >= minimumNumberOfEntries).Select(x => x.Key);

ddanbe commented: Thanks for your time and your knowledge! +15
kplcjl 17 Junior Poster

One of the nice things C# has is the XML documentation. What's nice about that is that it activates intellisence so you can document it. Renaming the int parameter as suggested is a good idea because even if it is in a dll, you don't have to correct your calling code to a better method name. What's great about the IDE tool is that it automatically builds the doc format when you type in ///. (An extreme pain when you are writing code in notepad. 1. For the formatting. 2. no intellisense.) That also organizes it so the documentation applies to the part you are documenting. That too, won't affect things calling the ddl.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.