Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 13 February 2014

Parallel Extensions to the .NET Framework

Parallel Sample :
In your opinion, how many CLR object can be created in one second? enter image description here 
See fallowing example :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ObjectInitSpeedTest
{
   class Program
   {
       //Note: don't forget to build it in Release mode.
       static void Main()
       {
           normalSpeedTest();           
           parallelSpeedTest();

           Console.ForegroundColor = ConsoleColor.White;
           Console.WriteLine("Press a key ...");
           Console.ReadKey();
       }

       private static void parallelSpeedTest()
       {
           Console.ForegroundColor = ConsoleColor.Yellow;
           Console.WriteLine("parallelSpeedTest");

           long totalObjectsCreated = 0;
           long totalElapsedTime = 0;

           var tasks = new List<Task>();
           var processorCount = Environment.ProcessorCount;

           Console.WriteLine("Running on {0} cores", processorCount);

           for (var t = 0; t < processorCount; t++)
           {
               tasks.Add(Task.Factory.StartNew(
               () =>
               {
                   const int reps = 1000000000;
                   var sp = Stopwatch.StartNew();
                   for (var j = 0; j < reps; ++j)
                   {
                       new object();
                   }
                   sp.Stop();

                   Interlocked.Add(ref totalObjectsCreated, reps);
                   Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);
               }
               ));
           }

           // let's complete all the tasks
           Task.WaitAll(tasks.ToArray());

           Console.WriteLine("Created {0:N} objects in 1 sec\n", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);
       }

       private static void normalSpeedTest()
       {
           Console.ForegroundColor = ConsoleColor.Green;
           Console.WriteLine("normalSpeedTest");

           const int reps = 1000000000;
           var sp = Stopwatch.StartNew();
           sp.Start();
           for (var j = 0; j < reps; ++j)
           {
               new object();
           }
           sp.Stop();

           Console.WriteLine("Created {0:N} objects in 1 sec\n", (reps / sp.ElapsedMilliseconds) * 1000);
       }
   }
}

Wednesday, 12 February 2014

Safe and Unsafe Code in C#

A particularly interesting feature of C# is its support for non-type-safe code. Normally, the common language runtime (CLR) takes on the responsibility for overseeing the behavior of Microsoft intermediate language (MSIL) code, and prevents any questionable operations. However, there are times when you wish to directly access low-level functionality such as Win32 API calls, and you are permitted to do this, as long as you take responsibility for ensuring such code operates correctly. Such code must be placed inside unsafe blocks in our source code.

C# code that makes low-level API calls, uses pointer arithmetic, or carries out some other unsavory operation, has to be placed inside blocks marked with the unsafe keyword. Any of the following can be marked as unsafe:
  • An entire method.
  • A code block in braces.
  • An individual statement.
The following example demonstrates the use of unsafe in all three of the above situations:
class TestUnsafe
{
unsafe static void PointyMethod()
{
int i=10;
int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}
static void StillPointy()
{
int i=10;
unsafe
{
int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}
}
static void Main()
{
PointyMethod();
StillPointy(); }
}
In this code, the entire PointyMethod() method is marked unsafe because the method declares and uses pointers. The StillPointy() method marks a block of code as unsafe as this block once again uses pointers.

In safe code, the garbage collector is quite free to move an object during its lifetime in its mission to organize and condense free resources. However, if your code uses pointers, this behavior could easily cause unexpected results, so you can instruct the garbage collector not to move certain objects using the fixed statement.
The following code shows the fixed keyword being used to ensure that an array is not moved by the system during the execution of a block of code in the PointyMethod() method. Note that fixed is only used within unsafe code:
class TestFixed
{
public static void PointyMethod(char[] array)
{
unsafe
{
fixed (char *p = array)
{
for (int i=0; i<array.Length; i++)
{
System.Console.Write(*(p+i)); }
} } }
static void Main()
{
char[] array = { 'H', 'e', 'l', 'l', 'o' };
PointyMethod(array);
}
}

Thursday, 6 February 2014

C# keywords rarely known Interview Questions


There are few words that we rarely use in day to day C# practices[I’m focusing readers who are beginners]. But I’ve seen them in either online exams or other IT quiz shows So I came to write something about those untouched keywords. Below is the list of these keywords

  • Implicit
  • Explicit
  • Volatile
  • Checked
  • Unchecked
  • Const vs ReadOnly [The most frequently asked Interview question for C# programmer]
Lets get to know about them which one is used where and when:

Implicit

The implicit keyword is used to declare an implicit user-defined type conversion operator. Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code. It eliminates unnecessary casts, implicit conversions can improve source code readability.
The below example you can see we’ve a CustomType that takes Integer value as its initializing value and after defining the Implicit operator It becomes directly castable to int.
image

However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness.

Explicit

As I mentioned sometimes implicit conversion can surprise you as it can go unnoticed. So in case you want to enforce an casting to be explicit then Explicit keyword is there. Again The explicit keyword is used to declare an explicit user-defined type conversion operator.
class MyType
    {
        public static explicit operator MyType(int i)
        {
            // code to convert from int to MyType
        }
    }
Unlike the Implicit it enforces the explicit cast to mention when a type is declared with conversion operator.
image

Volatile:

Volatile is kept under the category of Modifiers. The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.
Syntax:

public volatile int i;
Behavior: The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. And due to such behavior  volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatilemodifier ensures that one thread retrieves the most up-to-date value written by another thread.
The type of a field marked as volatile is restricted to the following types:
  • Any reference type.
  • Any pointer type (in an unsafe context).
  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

 

Checked and Unchecked:

Before we start I want to show you some code:

public static void Main() {     short x = 32767;   // Max short value    short y = 32767;     int z = 0;     //perform the sum and try cast it back to short before assigning     z = (short)(x + y);    Console.WriteLine("Checked output value is: {0}", z);     Console.Read(); }
Output:
image?????????????????????
Are you expecting this output in you application or Program. Better you throw an exception if you system is dealing with sensitive data. If you think so.. then use Checked.
Syntax:
checked(expression)
Now modify the above code like this:
try {     z = checked((short)(x + y)); } catch (System.OverflowException e) {     System.Console.WriteLine(e.ToString()); }
Now see the output:
imageImportant Note: In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions.
Similarly if you want to Skip such check always if your application or logic is flexible and ineffective by the resulting values then use unchecked.
Syntax:
unchecked (expression)

int z = unchecked((short)(x + y));
Output would be the same as we had without using checked.
image
if neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.

const vs readonly

So here we are at Interview Question. I’m sure these words are mostly used in code. So I’m not going show any demo for their use but to discuss some interesting answers that your interview would like Winking smile.
const value type
  • must be initialized
  • initialization must be at compile time
A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.
Constants must be a value type (sbytebyteshortushortintuintlongulongchar,floatdoubledecimal, or bool), an enumeration, a string literal, or a reference to null.
readonly value type
  • It can use default value, without initializing
  • initialization can be at run time

  • can be initialized either at the declaration or in a constructor
A read only member is like a constant in that it represents an unchanging value. The difference is that areadonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
I hope this post provide some quick and useful information to those who are beginners in C#.