Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C#
Tip/Trick

Logical and arithmetic operations in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (4 votes)
26 Jun 2011CPOL2 min read 41.7K   8   8
Some logical and arithmetic operations in C#

There are many uses of logical and arithmetic operators in C#. And also the usage of these operators are different
depending on the situation. For example, here is a simple use of the && operator:


C#
bool booleanResult = MethodReturnBooleanOne() && MethodReturnBooleanTwo() && MethodReturnBooleanThree();

and a simple use of the + operator:


C#
int result = MethodIntReturn1() + MethodIntReturn2() + MethodIntReturn3() + MethodIntReturn4();

We could delegate this logical operation( && or ||) on a specific method and let the method
do the operation and pass back the result to the caller. Also, it is possible to do the same for an arithmetic operation, for example,
3+5+5+5 could be done by just calling a method and passing 3,5,5,5 to that method, and the method will do the job and return back
the result to the caller. To describe the whole point, I created a few methods; for example:


C#
DoSequenceOfAnd(params bool[] sequenceOfBooleanValue)

This method will take the values of boolean and will do an && (AND) operation on those values and return the result to the caller.


C#
DoSequenceOfOr(params bool[] sequenceOfBooleanValue)

This method will take the values of boolean and will do an || (OR) operation on those values and return the result to the caller.


C#
DoSequenceOfXOr(params bool[] sequenceOfBooleanValue)

This method will take the values of boolean and do an ^ (XOR) operation on those values and return the result to the caller.


C#
DoSequenceOfPlus<T>(params T[] sequenceOfTValues)

This generic method will accept a sequence of values (in here, T should only define numeric types from the value types)
and will do an addition operation and return the result.


C#
DoSequenceOfMultiply<T>(params T[] sequenceOfTValues)

This generic method will accept a sequence of values (in here, T should only define numeric types from the value types)
and will do a multiplication operation and return the result.


Here is the code for the above methods:


C#
public static class Operation
{
    public static bool DoSequenceOfAnd(params bool[] sequenceOfBooleanValue)
    {
        bool andResult = true;
        Array.ForEach(sequenceOfBooleanValue,
            (item) =>
            {
                andResult &= item;
            });
        return andResult;
    }
    public static bool DoSequenceOfOr(params bool[] sequenceOfBooleanValue)
    {
        bool orredResult = default(bool);
        Array.ForEach(sequenceOfBooleanValue,
            (item) =>
            {
                orredResult |= item;
            });
        return orredResult;
    }
    public static bool DoSequenceOfXOr(params bool[] sequenceOfBooleanValue)
    {
        bool xoredResult = default(bool);
        Array.ForEach(sequenceOfBooleanValue,
            (item) =>
            {
                xoredResult ^= item;
            });
        return xoredResult;
    }
    public static T DoSequenceOfPlus<T>(params T[] sequenceOfTValues)
        where T : struct
    {
        T additionResult = default(T);
        Func<T, T, T> adder = ExpressionGenerator.AdditionExpression<T>();
        Array.ForEach(sequenceOfBooleanValue,
            (item) =>
            {
                additionResult = adder(item, additionResult);
            });
        return additionResult;
    }
    public static T DoSequenceOfMultiply<T>(params T[] sequenceOfTValues)
        where T : struct
    {
        dynamic multiplicationResult = (DoSequenceOfPlus<int>(default(int), 1));
        Func<T, T, T> multiplier = ExpressionGenerator.MultiplicationExpression<T>();
        Array.ForEach(sequenceOfBooleanValue,
            (item) =>
            {
                multiplicationResult = multiplier(item, multiplicationResult);
            });
        return multiplicationResult;
    }
}

Here is the usage of the above methods:


C#
static void Main(string[] args)
{
    bool booleanResult = MethodOne() && MethodTwo() && MethodThree();
    bool resultAnd = Operation.DoSequenceOfAnd(MethodOne(), MethodTwo(), MethodThree());
    bool resultOr = Operation.DoSequenceOfOr(MethodOne(), MethodTwo(), MethodThree());
    bool resultXOr = Operation.DoSequenceOfXOr(MethodOne(), MethodTwo(), MethodThree());
    int resultOfIntAddition = Operation.DoSequenceOfPlus<int>(3, 3, 5, 5);
    int resultOfIntMultiplication = Operation.DoSequenceOfMultiply<int>(3, 3, 3, 1);
    long resultOfLongMultiplication = Operation.DoSequenceOfMultiply<long>(1, 3, 1, 1);
}

and related code used by the DoSequenceOfPlus and DoSequenceOfMultiply methods:


C#
public static class ExpressionGenerator
{
    public static Func<T, T, T> AdditionExpression<T>()
    {
        ParameterExpression
           parameterA = Expression.Parameter(typeof(T), "a"),
           parameterB = Expression.Parameter(typeof(T), "b");
        BinaryExpression body = Expression.Add(parameterA, parameterB);
        return Expression.Lambda<Func<T, T, T>>(body, parameterA, parameterB).Compile();
    }
    public static Func<T, T, T> MultiplicationExpression<T>()
    {
        ParameterExpression
            parameterA = Expression.Parameter(typeof(T), "a"),
            parameterB = Expression.Parameter(typeof(T), "b");
        BinaryExpression body = Expression.Multiply(parameterA, parameterB);
        return Expression.Lambda<Func<T, T, T>>(body, parameterA, parameterB).Compile();
    }
}

To browse or download the source code, please visit here[^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia

Comments and Discussions

 
GeneralYou have worked hard for this, showed good examples but I ag... Pin
All Time Programming4-Jul-11 20:41
All Time Programming4-Jul-11 20:41 
You have worked hard for this, showed good examples but I agree with RakeshMeena & Philippe Mori, this is good for begineers to understand the use of operators; but in practical one would never use such a way to find results. Keeping a look on complexity, performance and unnecessary calls of methods, one would never approach such methodology. Like in DoSequenceOfOr, if first method returns true then the whole operation will be true only, then why still need to excute the other 2 methods to look for their results! This simply takes more time then a normal operation doing the same functionality.
GeneralAnother problem with your solution is that every time a new ... Pin
Philippe Mori28-Jun-11 15:44
Philippe Mori28-Jun-11 15:44 
GeneralReason for my vote of 4 The question in itself is not so bad... Pin
Philippe Mori28-Jun-11 15:32
Philippe Mori28-Jun-11 15:32 
GeneralIt would be interesting to see the performance comparison of... Pin
Philippe Mori28-Jun-11 15:07
Philippe Mori28-Jun-11 15:07 
GeneralTried to separate the logical operation code into a dedicate... Pin
Mohammad A Rahman28-Jun-11 2:08
Mohammad A Rahman28-Jun-11 2:08 
GeneralI don't think I understand what the problem is that you are ... Pin
tallies28-Jun-11 1:36
tallies28-Jun-11 1:36 
GeneralThis might be good for academic purpose but not of any pract... Pin
RakeshMeena26-Jun-11 19:22
RakeshMeena26-Jun-11 19:22 
GeneralReason for my vote of 1 This seems like a pretty bad way of ... Pin
Ed Nutting26-Jun-11 0:33
Ed Nutting26-Jun-11 0:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.