Sunday, 29 July 2012

Working With Arrays in C#



1            Arrays are reference types and are allocated memory on heap.
2            Every element of an array is automatically initialized to a default value based on its data type.
3            They are always dynamic because we can SET the size of the arrays at runtime.
4            Size of array can never be changed at runtime but we can create a new array with new length and copy the data from old array into new array.
5            Trying to access an element of array with invalid index throws IndexOutofRangeException Exception.
6            All arrays irrespective of their type are by default inherited from System. Array class
7            In C# we can have arrays of arrays and those are referred as Jagged Arrays. Here every element of the first array elements refers to another array and each one of them can be of different length


Single-Dimensional Arrays
int [] myArray = new int [5];
string []myStringArray = new string[5];

When you initialize an array upon declaration, it is possible to use the following shortcuts:
int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};

It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:
int[] myArray;
myArray = new int[] {1, 3, 5, 7, 9};   // OK
myArray = {1, 3, 5, 7, 9};   // Error
weekdays = new string[] {“Sunday”, “Monday”, “Tuesday”};

Multi-Dimensional Arrays
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];
You can initialize the array upon declaration as shown in the following example:
int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:
int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:
int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};   // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Program to use arrays:
using System;
class Program
{
    static void Main(string[] args)
    {
        int[] ar = new int[] { 1, 2, 3, 4 };
        Console.WriteLine(ar.Length);
        Console.WriteLine(ar.Rank); //Prints Number of Dimensions in array.
        foreach (int n in ar)
            Console.WriteLine(n);
    }
}
Code: 3.9
C#


Program: To read a list of numbers separated by space and print the Average of all those numbers.
using System;
class ProgramForMaxOfAnyNumbers
{
    static void Main(string[] args)
    {
        string str = Console.ReadLine();
        string[] ar = str.Split(' ');
        int sum = 0;
        for (int i = 0; i < ar.Length; i++)
        {
            sum += int.Parse(ar[i]);
            Console.WriteLine(ar[i]);
        }
        Console.WriteLine("Average: " + 1.0 * sum / ar.Length);
    }
}
Code: 3.10
C#



Program: To read length and data for an array from keyboard print the same.
using System;
class ProgramForMaxOfAnyNumbers
{
    static void Main()
    {
        Console.Write("Enter the array length: ");
        int n;
        n = int.Parse(Console.ReadLine());
        int[] ar = new int[n];
        for (int i = 0; i < n; i++)
        {
            Console.Write("Enter the " + i + "th value: ");
            ar[i] = int.Parse(Console.ReadLine());
        }
        for (int i = 0; i < ar.Length; i++)
        {
            Console.Write(ar[i] + " ");
        }
    }
}
Code: 3.11
C#


----------------------------------------------------------------------------------------------------------------------------------
Tricky Question:
LETS SEE WHAT IS THE OUTPUT OF THE FOLLOWING PROGRAM
class Program
{
        static void Main(string[] args)
        {
            int[] mar1, mar2;
            mar1 = new int[] { 1, 2 };
            mar2 = new int[] { 1, 2 };
            Foo(mar1, ref mar2);
            Console.WriteLine(mar1[0] + " " + mar1[1]);
            Console.WriteLine(mar2[0] + " " + mar2[1]);
        }

        static void Foo(int[] ar1, ref int []ar2)
        {
            ar1[0]++;
            ar2[0]++;
        }
}

LETS KEEP THE DISCUSSION ON...
I WOULD REQUEST YOU TO RUN THE PROGRAM FIND THE ANSWER AND POST YOUR COMMENT WITH REASON...

I WILL PROVIDE THE REASON ONCE I HAVE SOME INPUTS HERE....

Loving You All.

Best of Luck.

Sunday, 22 July 2012

Significance of System.Object DataType

·         System.Object is a Common Type System to which any value can be assigned.
·         Both Value Type and Reference Types can be assigned to variable of type object.
·         It’s a Reference Type. It can holds reference to any object on Heap memory.

Let’s understand how Value Type’s and Object Type are related.
·        Any value type including byte, short, int, long, float, double, decimal, char, bool, any enum and structure can be assigned to variable of type Object and this is called as Boxing.
·        Boxing is the term used to describe the transformation from any Value Type to Object which is a Reference Type. The runtime creates a temporary reference-type box for the object on the heap.
·        UnBoxing is the term used to describe the transformation from reference type (Object) to value type.  We use the term cast here, as this has to be done explicitly.
·        Boxing / Unboxing should be used only in situations where until runtime we don’t know the type of data we are going to deal with.
·         When a value is boxed to an object type, the object type variable cannot be used in any mathematical operations.
·        When the value of object type variable cannot be assigned to variable on LHS, an Exception is thrown.
·        Excessive usage of Object data type makes the language “Loosely Typed” and also because of frequent casting requirement while Boxing and Unboxing performance is also degraded.

class Program
{
    static void Main(string[] args)
    {
        object ob;
        int n, m;
        n = 10;
        ob = n; //Boxing - *1
        m = (int)ob; //Unboxing - *2
        string s = "Demo";           
        ob = s; // This is not boxing - *3
    }
}

*1. Explanation:
·         “n” is a local variable and is allocated memory on stack of Main and the value assigned to it is 10.
·         ob is also a local variable and allocated memory on stack of Main
·         This value of n, which is 10 is then copied on Heap and reference to it is assigned to the variable “ob”.
·         Because the value is on Heap and referenced by “ob” it is called “Boxing”

*2. Explanation
·         “m” is a local variable and is allocated memory on stack of Main.
·         The value on the heap i.e 10, referenced by “ob” is copied to the location where variable “m” is stored. This is called as Unboxing.

*3. Explanation
·         Here “Demo” is a string and string’s being Reference Types are always allocated memory on Heap.
·         The reference to the string is assigned to variable and same reference is assigned to “ob”.
·         No copy of “s” is created. Same Value “Demo” is what “ob” referrers to.
·         This is Not Boxing nor Unboxing.


Let’s understand Object as Reference Type
·         Every class in .NET is inherited from System.Object class.
·         Because of this following are true about Object.
o   Variable of type object can reference to object of any class.
o   The functionality of Object class is available to all the objects in .NET.

Methods in Object class:
1.       bool Equals(object obj) // Compares the current object reference with obj and returns true if both are referring to the same object otherwise returns false.
2.       System.Type GetType() //returns the Type instance for the current objects class.
3.       int GetHashCode() //return a unique number using which CLR identifies the current object.
4.       string ToString() //return the class name of the current object.

Note: ToString, Equals and GetHashCode are virtual and can be overridden in any class.

Example:
class Demo
{
    public int N;
    public override string ToString()
    {
        return N.ToString();
    }
    public override bool Equals(object obj)
    {
        Demo d = (Demo)obj;
        return this.N == d.N; //Instead of comparing reference we want to compare state of objects
    }
}
class Program
{
    static void Main(string[] args)
    {
        Demo d1 = new Demo() { N = 10 };
        Console.WriteLine(d1.ToString()); // Prints 10

        Demo d2 = new Demo { N = 10 };
        Console.WriteLine(d1.Equals(d2)); // Prints True
       
        Type t1 = d1.GetType();
        Type t2 = d2.GetType();
        Console.WriteLine(d1 == d2); //Prints True
    }
}

ToString:
·         If ToString is not overridden in Demo class then default implementation as in object class returns class name and thus it prints “Demo”
·         If ToString is overridden, then it prints “10” – value of N as returned by ToString.

Equals
·         If Equals is not overridden then in Demo class the it prints “False” because both d1 and d2 are referencing to two different object and default implementation of Equals in object class returns true only if both the current and parameter variables refers to the same objects.
·         If Equals is overridden as in the above example it prints “True” because we are not comparing the value of the members of object reference by current and parameter variables and they are same i.e. 10.

GetHashCode
·         Default implementation returns a unique number which is the identity of the object in CLR.
·         If Equals is overridden it is recommended to override GetHashCode also and you can find a good explanation about why from http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c.

GetType:
·         It’s not a virtual method and thus cannot be overridden.
·         Every Type when loaded has an instance of class System.Type is created.
·         All objects of similar type have same Type instance.