C#.NET

Difference between int, Int16, Int32 and Int64


In the learning phase developer are not much aware of the difference between primitive, FCL (framework class library), reference, and value types. This cause bugs and performance issues into the code. In this article, I would like to expose the different behavior of integer type.

int

  1. It is a primitive data type defined in C#.
  2. It is mapped to Int32 of FCL type.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int16

  1. It is a FCL type.
  2. In C#, short is mapped to Int16.
  3. It is a value type and represent System.Int16 struct.
  4. It is signed and takes 16 bits.
  5. It has minimum -32768 and maximum +32767 capacity.

Int32

  1. It is a FCL type.
  2. In C#, int is mapped to Int32.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int64

  1. It is a FCL type.
  2. In C#, long is mapped to Int64.
  3. It is a value type and represent System.Int64 struct.
  4. It is signed and takes 64 bits.
  5. It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 capacity.

Note

  1. A number of developers think that int represents a 32-bit integer when the application is running on a 32-bit OS and it represents a 64-bit integer when the application is running on a 64-bit OS. This is absolutely wrong.
  2. In C# int is a primitive data type and it always mapped to System.Int32 whether the OS is 32-bit or 64-bit.

Swapping of 2 Numbers without using 3rd Variable


In this post we will see how to swap two numbers without using third variable. Check below sample codes.

1. Using (+,-)

a = a+b = 4+5 = 9     // Should Not Overflow
b = a-b = 9-5 = 4
a = a-b = 9-4 = 5

2. Using (*,/)

a = a*b = 4*5 = 20    // Should Not Overflow
b = a/b = 20/5 = 4    // Should Not Overflow and Should Not be Irrational Number
a = a/b = 20/4 = 5    // Should Not Overflow and Should Not be Irrational Number

VB.NET Example :

Module SwappingDemo
    Sub main()
        Dim a, b As Integer
        Console.Write("Enter the values of a and b:")
        a = CInt(Console.ReadLine())
        b = CInt(Console.ReadLine())
        Console.WriteLine("Before swapping values of a=" + a.ToString() + " b=" + b.ToString())
        a = a + b
        b = a - b
        a = a - b
        Console.WriteLine("After swapping values of a=" + a.ToString() + " b=" + b.ToString())
        Console.ReadLine()
    End Sub
End Module

C#.NET Example

static class SwappingDemo
{
	public static void main()
	{
		int a = 0;
		int b = 0;
		Console.Write("Enter the values of a and b:");
		a = Convert.ToInt32(Console.ReadLine());
		b = Convert.ToInt32(Console.ReadLine());
		Console.WriteLine("Before swapping values of a=" + a.ToString() + " b=" + b.ToString());
		a = a + b;
		b = a - b;
		a = a - b;
		Console.WriteLine("After swapping values of a=" + a.ToString() + " b=" + b.ToString());
		Console.ReadLine();
	}
}

Boxing and Unboxing


Boxing: Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.

  • It converts a value type into a reference type.
  • Values are stored in the Stack first then moved to the heap.
  • Creates a container/box for holding the value.

Unboxing: Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

  • It is the opposite process of boxing.
  • It converts an object type back into the value type.
  • It is an explicit operation using C-style casting.

Example

namespace BoxingUnboxing
{
    class Program
    {
        static void Main(string[] args)
        {
            int Val = 1;
            Object Obj = Val;		//Boxing
            int i = (int)Obj;		//Unboxing
            Console.WriteLine("Boxing: {0}", Obj);
            Console.WriteLine("Unboxing: {0}", i);
            Console.ReadLine();
        }
    }
}

Note:

Sometimes boxing is necessary, but you should avoided it if possible, since it will slow down the performance and increase memory requirements.
For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and required extra memory (around twice the memory of the original value type).

Value Type and Reference Types


typesinnetThe Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.

Value Types

value_typeA Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Predefined datatypes, structures, enums are also value types, and work in the same way. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can’t access the stack.

Examples : int, enum, structs.  

(more…)

ASP.NET – Calendar Control


Adding a calendar in ASP.NET and displaying it in a webpage is not difficult. One of my friend asked me about the same because he never used this control. So he asked me about sample or demo of Calender Control in ASP.NET.

The Calendar control is a functionally rich web control, which provides the following capabilities

  • Displaying one month at a time
  • Selecting a day, a week or a month
  • Selecting a range of days
  • Moving from month to month
  • Controlling the display of the days programmatically

The basic syntax of a calendar control is :

<asp:Calender ID = "Calendar1" runat = "server">
</asp:Calender>

(more…)

Calculate Fibonacci Series in Various Ways Using C#


This is one of the most asked question in interviews, calculating and printing Fibonacci series. Let’s first try the iterative approach that is simple and prints all the Fibonacci series by passing the length as parameter.

Note :  We are starting the series from 0 (instead of 1).

public static void FibonacciIterative(int length)
{
	int a = 0, b = 1, c = 0;
	Console.Write("{0} {1}", a,b);
	for (int i = 2; i &lt; length; i++)
	{
		c = a + b;
		Console.Write(" {0}", c);
		a = b;
		b = c;
	}
 }

Test Input : FibonacciIterative(10);

Output : 0 1 1 2 3 5 8 13 21 34 (more…)

Introduction to Generics in C#


Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. (more…)