Friday 10 February 2012

C# Data types

In C#.net language there are 4 types of data types and 2 of which are common because of their using in programming. These 2 commonly used data types are int and float. Now, int types are categorized into two forms these are signed and unsigned. Signed data types are those data types which can store negative value as well as positive value, but Unsigned data types can store only positive values.
The values range of the different data types as follows.

Types AliasAllowed Values
sbyteSystem.SByte-128 to 127
byteSystem.Byte0 to 255
shortSystem.Int16-32,768 to 32,767
ushortSystem.UInt160 to 65,535
intSystem.Int32-2,147,483,648 to 2,147,483,648
uintSystem.UInt320 to 4,294,967,295
longSystem.Int64-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulongSystem.UInt640 to 18,446,744,073,709,551,615

Here in the table s stands for signed data types and u stands for unsigned data types.

Now, we also need to store floating point values, for that we need float data types. There are basically three types of floating point data types and these are: float, double and decimal. Here the values range table of floating point data types:

TypesAlias For App. max range App. min range
floatSystem.Single1.5 x 10-45 3.4 x 1038
doubleSystem.Double 5.0 x 10-324 1.7 x 10308
decimalSystem.Decimal1.0 x 10-287.9 x 1028

  
Here three other simple types are available. These are:
              
TypesAlias forAllowed Values
charSystem.Char0 to 65,535
boolSystem.Booleantakes only true or false
stringSystem.Stringtakes only number or sequence
 of characters like "Microsoft"


C# data types are similar to Java but with little difference. 

Wednesday 8 February 2012

.NET 4.0

.NET 4.0 (2010) is the new framework after release of 3.5 (2007) version. In .NET 4.0 we get Parallel Linq and Task Parallel Library. In Linq you are working with objects. Linq query operations on three distinct actions:
a) obtain the data source.
b) create the query
c) execute the query.

Here is the Example of Linq Query in C#.Net:

class IntroToLINQ
{        
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable<int>
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQuery)
        {
            Console.Write("{0,1} ", num);
        }
    }
}

Parallel Linq is basically for speeds up the execution of LINQ to Objects queries by executing the query delegates in parallel on multi-core computers

You can get further reading for Linq topics in (LINQ to Sql).

Now, We start about what is TPL Task Parallel Library.
Task Parallel Library is the set of public type of API's in System.Threading and System.Threading.Tasks namespaces in .Net 4. By using TPL developers can be more productive in the field of development of applications by using parallelism and concurrency to applications. By using TPL technique applications can handles the partitioning of work.the scheduling of threads on the ThreadPool, state management. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Here, the example of  simple parallel.For Loop

namespace MultiplyMatrices
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    class Program
    {
        #region Sequential_Loop
        static void MultiplyMatricesSequential(double[,] matA, double[,] matB,
                                                double[,] result)
        {
            int matACols = matA.GetLength(1);
            int matBCols = matB.GetLength(1);
            int matARows = matA.GetLength(0);

            for (int i = 0; i < matARows; i++)
            {
                for (int j = 0; j < matBCols; j++)
                {
                    for (int k = 0; k < matACols; k++)
                    {
                        result[i, j] += matA[i, k] * matB[k, j];
                    }
                }
            }
        }
        #endregion

        #region Parallel_Loop

        static void MultiplyMatricesParallel(double[,] matA, double[,] matB, double[,] result)
        {
            int matACols = matA.GetLength(1);
            int matBCols = matB.GetLength(1);
            int matARows = matA.GetLength(0);

            // A basic matrix multiplication.
            // Parallelize the outer loop to partition the source array by rows.
            Parallel.For(0, matARows, i =>
            {
                for (int j = 0; j < matBCols; j++)
                {
                    // Use a temporary to improve parallel performance.
                    double temp = 0;
                    for (int k = 0; k < matACols; k++)
                    {
                        temp += matA[i, k] * matB[k, j];
                    }
                    result[i, j] = temp;
                }
            }); // Parallel.For
        }

        #endregion


        #region Main
        static void Main(string[] args)
        {
            // Set up matrices. Use small values to better view 
            // result matrix. Increase the counts to see greater 
            // speedup in the parallel loop vs. the sequential loop.
            int colCount = 180;
            int rowCount = 2000;
            int colCount2 = 270;
            double[,] m1 = InitializeMatrix(rowCount, colCount);
            double[,] m2 = InitializeMatrix(colCount, colCount2);
            double[,] result = new double[rowCount, colCount2];

            // First do the sequential version.
            Console.WriteLine("Executing sequential loop...");
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            MultiplyMatricesSequential(m1, m2, result);
            stopwatch.Stop();
            Console.WriteLine("Sequential loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds);

            // For the skeptics.
            OfferToPrint(rowCount, colCount2, result);

            // Reset timer and results matrix. 
            stopwatch.Reset();
            result = new double[rowCount, colCount2];

            // Do the parallel loop.
            Console.WriteLine("Executing parallel loop...");
            stopwatch.Start();
            MultiplyMatricesParallel(m1, m2, result);
            stopwatch.Stop();
            Console.WriteLine("Parallel loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            OfferToPrint(rowCount, colCount2, result);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }


        #endregion

        #region Helper_Methods

        static double[,] InitializeMatrix(int rows, int cols)
        {
            double[,] matrix = new double[rows, cols];

            Random r = new Random();
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = r.Next(100);
                }
            }
            return matrix;
        }

        private static void OfferToPrint(int rowCount, int colCount, double[,] matrix)
        {
            Console.WriteLine("Computation complete. Print results? y/n");
            char c = Console.ReadKey().KeyChar;
            if (c == 'y' || c == 'Y')
            {
                Console.WindowWidth = 180;
                Console.WriteLine();
                for (int x = 0; x < rowCount; x++)
                {
                    Console.WriteLine("ROW {0}: ", x);
                    for (int y = 0; y < colCount; y++)
                    {
                        Console.Write("{0:#.##} ", matrix[x, y]);
                    }
                    Console.WriteLine();
                }

            }
        }

        #endregion
    }

}