Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Friday, 29 May 2015

BOXING AND UNBOXING

Today in Engineer's World, we are discussing a very important topic of C# - Boxing and Unboxing in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

Welcome friends, the Blog is to explain Boxing and Unboxing. Confusing and useless terms for beginner's and even for some professional too.



In C# how can we convert one type to another? The first idea that comes to your mind is by using implicit or explicit conversion and type casting. But can we convert a value of one type into a value of another type? Can we? Answer is yes.

The process of converting a value type to a reference type is called boxing. The inverse process, converting a reference type to a value type, is called unboxing. This is illustrated in the following code:

int i = 58959; // a value type  
object o = i; // boxing  
int j = (int)o; // unboxing

What is object? And why object is so much important in box and unbox? object (Go to Definition) is derive from Object class. It supports all classes in .Net Framework class hierarchy and provides low-level class hierarchy to derived classes. This is the ultimate base class for all classes it the .Net Framework; it is the root of the type hierarchy.

Boxing:
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object.

Rules of Boxing:
-> No need to tell the compiler that you are boxing from value to reference. Because compiler take care of it. It is implicit.
using System;

namespace AspnetSolutions
{
    class Boxing
    {
        public static void Main()
        {
            DateTime presentdate1 = DateTime.Now;  //Part1
            object obj1 = presentdate1;  //You can directly pass (Implicitly)
            Console.WriteLine(obj1);


            char name = 'A';  //Part2
            object obj2 = name;
            Console.WriteLine(obj2);

            int number = 25;  //Part3
            object obj3 = number;
            Console.WriteLine(obj3);
        }
    }
}

  
Output:
The output is very straight forward. 
In Part 1 we are taking the DateTime.
In Part 2 we are taking the character (char). 
In Part 3 we are taking the integer. 



UnBoxing:
Unboxing is used to store reference type in stack. Unboxing is an explicit conversion of reference type to the value type.



Rules of Unboxing:
1. We can only unbox a value that has previously been boxed.

using System;

namespace AspnetSolutions
{
    class Unboxing
    {
        public static void Main()
        {
            try
            {
                int i = 25;
                object o = i;

                long l = (long)o;
                Console.WriteLine("i: " + i);
                Console.WriteLine("o: " + o);
                Console.WriteLine("l: " + l);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


Output:
We get error Message- Specified Cast is not valid (InvalidCastException). Because we have intialized variable i as integer and during unbox we explicit want our variable to long data type. 
 


2. Before unboxing C# checks that value type we request is actually stored in the object under conversion, only then the value is unboxed.
3. Unboxing copies the value out of the object. It doesn't manipulate the value.

using System;

namespace AspnetSolutions
{
    class free
    {
        public static void Main()
        {
            int i = 25;
            Console.WriteLine("Initial value of i = " + i);
            object o = i;
            i = (int)o;  //Unboxing

            Console.WriteLine("Value of o = " + o);
            Console.WriteLine("After Unboxing the value of i = " + i);
        }
    }
}


Output:
You can notice that just before Unboxing the value of o is 25 and after that value is same for i = 25. Means it copies the value out of the object.




To read STRING in C# (Declaration and Initialization) PART-1 - Click here.

Related Questions:-

#newtoprgm try first program

Q-1 Choose correct type of variable scope for given defined variables.

 class ABC
  {
      static int m;
      int n;
      void fun (int x , ref int y, out int z, int[] a)
      {
         int j = 10;
      }
  }

Scope declaration:
 

A) m = static variable, n = local variable, x = output parameter, y = reference parameter, j = instance variable, z =output parameter, a[0]= array element
 

B) m = static variable, n = instance variable, x = value parameter, y = reference parameter, j = local variable, z =output parameter , a[0] = array element
 

C) m = static variable, n = instance variable, x = reference parameter, y = value parameter, j = local variable, z =output parameter, a[0] = array element
 

D) m = local variable, n = instance variable, x = reference parameter, y = value parameter, j = static variable, z =output parameter, a[0] = array element  

Ans- Option(B)
Explanation- By definition of scope of variables.

Q-2 Correct output for following set of code is:

    public static void Main(string[] args)
    {
        int i = 123;
        object o = i;
        i = 456;
        System. Console. WriteLine("The value-type value = {0}", i);
        System. Console. WriteLine("The object-type value = {0}", o);
        Console. ReadLine();
    }

A) 123, 123
B) 456, 123
C) 456, 456
D) 123, 456


Ans- Option(B).
Explanation-
The concept of boxing is implemented here. The variable ‘i’ of ‘int’ type is boxed using variable ‘o’ of object type and hence value stored inside it is initialized to the object variable ‘o’. In Next, variable ‘i’ is again initialized with some value overriding its previous stored value.
Output-
456, 123


Click imaginationhunt.blogspot to see latest Blogs

Q-3 Correct output for following set of code is:

  public static void Main(string[] args)
  {
      int i = 546;
      object o = i;
      int n =(int) o;
      o = 70;
      System. Console. WriteLine("The value-type value = {0}", n);
      System. Console. WriteLine("The object-type value = {0}", o);
      Console. ReadLine();
  }

A) 546, 0
B) 546, 546
C) 546, 70
D) 70, 546

Ans- Option(C).
Explanation-
The concept of ‘unboxing’ is implemented here. To ‘unbox’ an object back to value type, we should have to do it explicitly as “int n = (int) o”.
Output-
546, 70


Keep learning and sharing!!!

Tuesday, 12 May 2015

USAGES OF REFERENCE DATA TYPES IN C#

Today in Engineer's World, we are discussing a very important topic of C# - Reference Data Type in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

A variable holds a reference to the value, then that type of data type is reference types. These reference types are stored in "heap" memory and these types are not fixed in size. They are maintained in System managed heap but it also uses stack to store reference of the heap. 

Two primitive types (string and object), and
Non-primitive data types (class, interface, delegates) are example of reference type.

REFERENCE DATA TYPES

Ex- class, interface, delegates, string, object and array.
Things to Remember:
a) Object type is superior to all types. It can store any type or any size of data. It helps in Inheritance process.

1. string: It represent text as a Unicode characters.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

For ex- 
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            string str1 = "Engineer's";
   //str1 store "Enginner's" which is nothing but text 
            string str2 = "World";
    //str2 store "World" which is nothing but text
            string result = str1 + str2;
            Console.WriteLine(result);
        }
    }
}

Output:
Engineer'sWorld


2. array: Array can use with any type.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex- Here we have used for loop to understand it better.
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {           
            int[] numbers={1,2,3,4,5,6,7,8,9,10};
            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine(numbers[i]);
            }
        }
    }
}

Output:
1
2
3
4
5
6
7
8
9
10

3. object: can store any type or any size of data
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            int a = 15;
            object obj = a;
            object obj1 = 150;
            object obj2 = "Hello";

            Console.WriteLine("a= {0}", a);
            Console.WriteLine(a.GetType());
            Console.WriteLine("obj= {0}", obj);
            Console.WriteLine(obj.GetType());
            Console.WriteLine("obj1= {0}", obj1);
            Console.WriteLine(obj1.GetType());
            Console.WriteLine("obj2= {0}", obj2);
            Console.WriteLine(obj2.GetType());
        }
    }
}
Output:
a= 15
System.Int32
obj= 15
System.Int32
obj1= 150
System.Int32
obj2= Hello
System.String

In C# it is possible to convert a value of one type into a value of another type. The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to.

To read Boxing and Unboxing in C# - Click here.

Related Questions:-

#newtoprgm try firstprogram

Q-1 Which of the following statements are correct about c# datatypes?
1. Every data type is either a value type or a reference type.
2. Value types are always created on the heap.
3. Reference types are always created on the stack.
4. Mapping of every value type to a type in CTS facilitates Interoperability in C#.
5. Every reference type gets mapped to a type in CTS.
A) 1, 3
B) 2, 5
C) 1, 4
D) 3, 4
Ans- Option(C).

Q-2 Which of the following statements are correct?
1. We can assign values of any type to variables of type object.
2. When a variable of a value type is converted to object, it is said to be unboxed.
3. When a variable of a object type is converted to value, it is said to be boxed.
4. Boolean variables cannot have a value of null.
5. When a value type is boxed, an entirely new object must be allocated and constructed.

A) 2, 5
B) 1, 5
C) 3, 4
D) 2, 3
Ans- Option (B)

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Monday, 11 May 2015

USAGE OF VALUE DATA TYPES IN C#

Today in Engineer's World, we are discussing a very important topic of C# -VALUE DATA in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

VALUE TYPE

A variable which holds actual values then that type of data types are value types. Value type are stored in "stack" memory and these value types are fixed in size.
Value type variables are local copies. When they fall out of the scope they may die. Value types are derived from System.ValueType.

VALUE DATA TYPES

Ex- byte, short, int, float, double, long, char, bool, DateTime.
Things to Remember:
a) Primitive data type are value type except string.object.
b) struct, enum are value types.
c) The default value, if value is not assigned is 0 for value type(i.e. whether it may int, long, short, char).

For ex- The default values for value types can be understand by the following example
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            int a1 = new int();
            Console.WriteLine(a1);

            char a2 = new char();
            Console.WriteLine(a2);


            short a3 = new short();
            Console.WriteLine(a3);

        }
    }
}

Output:
0 //for int default is 0.
   //for char it is ' '.
0 //for short it is 0.

Now, check out Figure 1. This is the most important chart or figure for understanding data types (types, namespace, size, low range of type, high range of type). Interviewer may also asked question like, tell the size in byte taken by decimal or does int variable can store a value 2145656565?
So, I strongly suggest you to look and read this chart to better under data type.


FIGURE-1

How to use these Data Type?
We will see all the Types one by one.

1. int: An integer is a number with no fractional part; it can be positive, negative or zero. It can store number up to a range that is mentioned in the figure. It represent a 32-bit signed integer.
Namespace & Assembly of type can be checked by Figure-2. All you need is place your mouse pointer on that data type and press F12. Then,  you would transfer to its definition. For example- place you mouse pointer on int in your code and Press F12. You will see a similar page as shown in Figure-2.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

FIGURE-2

For ex- So, let's see how to use int data type.
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            int a = 9;
            int b = 7;
            int result = a + b;
            Console.WriteLine(result);
        }
    }
}

Output:
16
/*This is how we use int type.*/

2. bool: Represent a boolean value. Boolean can have only two value it may be true or false.
By default value is false.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            bool a=new bool();
            if (a == true)
            {
                Console.WriteLine("result true");
            }
            else
            {
                Console.WriteLine("result false");
            }
        }
    }
}

Output:
result false 

3. char: To represent a single unicode character.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            char a = 'A';

            Console.WriteLine(a);
        }
    }
}

Output:
A

Click imaginationhunt.blogspot to see latest Blogs

4. byte: It represent an 8-bit unsigned integer.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            //byte a = -5;  /*negative number are not in range*/
            //byte b = 3595;    /*larger number are not in range*/
            byte c = 255;
            //byte d = 256;    /*number greater than 255 are not in range*/
            Console.WriteLine(c);
        }
    }
}

Output:
255

5. short: It represent an 16-bit signed integer.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            short a = 25;
            Console.WriteLine(a);
        }
    }
}

Output:
25
 


6. float: It represent a single precision floating point number. Float is used to store integer and fractional numbers. But in case of fractional number 'f' would be add to its end.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            float a = 25;
            Console.WriteLine(a);

            float b = 25.6f;
            Console.WriteLine(b);
        }
    }
}

Output:
25
25.6
 


7. double: It represent a double precision floating point number.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            double a = 25;
            Console.WriteLine(a);

            double b = 25.6;  /*fractional value are accepted without f, means without 25.6f*/
            Console.WriteLine(b);
        }
    }
}

Output:
25
25.6

8. long: It represent a 64-bit signed integer. 'long' is used to store large number as the range of this type is very large.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-
using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            long a = 25;
            Console.WriteLine(a);

            //long b = 25.6;   /*fractional value are not accepted*/
            //Console.WriteLine(b);
        }
    }
}

Output:
25

9. DateTime: is used for store and retrieve time. 
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
For ex-

using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            DateTime presentdatetime = DateTime.Now;
            Console.WriteLine(presentdatetime);
        }
    }
}

Output:
5/10/2015 1:19:27 AM

In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to.

To read Usage of Reference Data Types in C# - Click here.

Related Questions:-

#newtoprgm try firstprogram

Q-1 Which of the following statement correctly assign a value 33 to a variable c?
byte a = 11, b = 22, c;

A) c = (byte) (a + b);
B) c = (byte) a + (byte) b;
C) c = (int) a + (int);
D) c = (int) (a + b);
E) c = a + b;
Ans- Option (A)

Q-2 Which of the following statements is correct?
short l = 20;
short m = 400;
int a;
a = l1 * l2;

A) A value 8000 will be assigned to a.
B) A negative value be assigned to a.
C) During arithmetic if the result exceeds the high or low value of the range, the value wraps around till the other side of the range.
D) An error is reported as widening conversion cannot takes place.
E) An overflow error will be reported since the result of the multiplication exceeds the range of a short integer.
Ans- Option(A).

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Sunday, 10 May 2015

DATA TYPES IN C#

Today in Engineer's World, we are discussing a very important topic of C# - Data Types in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

DATA TYPES

Data Type in a programming language describes that what type of data a variable can hold. The type of data that a variable contains is called Data Type.
C# is a Strongly type typed language so every variable and object must have a type.

C# DATA TYPES

1. Basic in-built or primitive or predefined:
Ex- byte, short, int, float, double, long, char, bool, DateTime, string, object,etc.

2. Non-primitive or User-defined:
Ex- enum, class, struct, interface, delegate, array.

The variables in C#, are categorized into the following types:
  • Value types
  • Reference types


VALUE TYPE:

A variable which holds the actual values then that type of data types are value types. Value type is stored in "stack" memory and these value types are fixed in size.
Value type variables are local copies. When they fall out of the scope they may die. Value types are derived from System.ValueType.
Ex- byte, short, int, float, double, long, char, bool, DateTime.
Things to Remember:
a) Primitive data type are value type except string.object.
b) struct, enum are value types.
c) The default value, if value is not assigned is 0 for value type(i.e. whether it may int, long, short, char). 

Click imaginationhunt.blogspot to see latest Blogs

Example- The default values for value types can be understand by the following example.

Practical Implementation 

using System;

namespace AspnetSolutions
{
    class Dtype
    {
        public static void Main()
        {
            int a1 = new int();
            Console.WriteLine(a1);

            char a2 = new char();
            Console.WriteLine(a2);


            short a3 = new short();
            Console.WriteLine(a3);

        }
    }
}



Output

0 //for int default is 0.
   //for char it is ' '.
0 //for short it is 0.

Now, check out Figure 1. This is the most important chart or figure for understanding data types (types, namespace, size, low range of type, high range of type). Interviewer may also asked question like, tell the size in byte taken by decimal or does int variable can store a value 2145656565?
So, I strongly suggest you to look and read this chart to better under data type.

FIGURE 1


Check out all types one by one:

1. int: An integer is a number with no fractional part; it can be positive, negative or zero. It can store number up to a range that is mentioned in the figure. It represent a 32-bit signed integer.
Namespace & Assembly of type can be checked by Figure-2. All you need is place your mouse pointer on that data type and press F12. Then, you would transfer to its definition. For example- place you mouse pointer on int in your code and Press F12. You will see a similar page as shown in Figure-2.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

FIGURE 2

2. bool: Represent a boolean value. Boolean can have only two value it may be true or false.
By default value is false.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

3. char: To represent a single unicode character.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)


4. byte: It represent an 8-bit unsigned integer.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)


5. short: It represent an 16-bit signed integer.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

Click imaginationhunt.blogspot to see latest Blogs

6. float: It represent a single precision floating point number. Float is used to store integer and fractional numbers. But in case of fractional number 'f' would be add to its end.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)


7. double: It represent a double precision floating point number.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

8. long: It represent a 64-bit signed integer. 'long' is used to store large number as the range of this type is very large.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

9. DateTime: is used for store and retrieve time. 
Namespace -System.
Assembly- mscorlib (mscorlib.dll)
  
REFERENCE TYPE:

A variable holds a reference to the value, then that type of data type are reference types. These reference types are stored in "heap" memory and these types are not fixed in size. They are maintained by System managed heap, but it also uses stack to store a reference of the heap.
Two primitive types (string and object), and
Non-primitive data types (class, interface, delegates) are example of reference type.
Ex- class, interface, delegates, string, object and array.
Things to Remember:
a) Object type is superior to all types. It can store any type or any size of data. It helps in Inheritance process.

1. string: It represent text as a Unicode characters.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

2. array: Array can use with any type.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)

3. object: can store any type or any size of data.
Namespace -System.
Assembly- mscorlib (mscorlib.dll)


In C# it is possible to convert a value of one type into a value of another type. The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to.



Related Questions: 

#newtoprgm try firstprogram

Q-1 Which of the following are correct about data types?
1. If the integer literal exceeds the range of byte, a compilation error will occur.
2. We cannot implicitly convert non-literal numeric types of larger storage size to byte.
3. Byte cannot be implicitly converted to float.
4. A char can be implicitly converted to only int data type.
5. We can cast the integral character code.

A) 1, 3, 5
B) 2, 4
C) 3, 5
D) 1, 2, 5
Ans- Option(D).


2. Which of the following is an 8-byte integer?
A) Char
B) Long
C) Short
D) Byte
E) Integer
Ans- Option(B).

3. Which of the following is the correct ways to set a value 3.14 in a variable pi such that it cannot be modified?
A) float pi=3.14F;
B) #define pi 3.14F;
C) const float pi = 3.14F;
D) const float pi; pi= 3.14F;
E) pi = 3.14F; 
Ans- Option(C).

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...












Featured post

Think that makes you rich and richer

 Napolean said: “You can think and grow rich, but if you can be brought up like most people with work and you won't starve, this wil...