.NET

All .NET Technologies

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…)

View State In ASP.NET


The view state is the state of the page and all its controls. It is automatically maintained across posts by the ASP.NET framework.

When a page is sent back to the client, the changes in the properties of the page and its controls are determined, and stored in the value of a hidden input field named _VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request.

The view state could be enabled or disabled for:

  • The entire application by setting the EnableViewState property in the <pages> section of web.config file.
  • A page by setting the EnableViewState attribute of the Page directive, as <%@ Page Language=”C#” EnableViewState=”false” %>
  • A control by setting the Control.EnableViewState property.

It is implemented using a view state object defined by the StateBag class which defines a collection of view state items. The state bag is a data structure containing attribute value pairs, stored as strings associated with objects.

The StateBag class has the following properties:

Properties Description
Item(name) The value of the view state item with the specified name. This is the default property of the StateBag class.
Count The number of items in the view state collection.
Keys Collection of keys for all the items in the collection.
Values Collection of values for all the items in the collection.

The StateBag class has the following methods:

Methods Description
Add(name, value) Adds an item to the view state collection and existing item is updated.
Clear Removes all the items from the collection.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows it to free resources and perform other cleanup operations.
GetEnumerator Returns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object.
GetType Gets the type of the current instance.
IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether it has been modified.
Remove(name) Removes the specified item.
SetDirty Sets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it.
SetItemDirty Sets the Dirty property for the specified StateItem object in the StateBag object.
ToString Returns a string representing the state bag object.

(more…)

Managing State In ASP.NET


States

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:

  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state
  • Profile Properties

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.
(more…)

Advantages of Razor View Engine


The Razor View Engine is an advanced view engine, available with MVC 3.0 and later versions. Razor uses the “@” character instead of “<% %>” as used by the ASPX View Engine. Razor does not require the code block to be closed, the Razor View Engine parsed itself and it is able to decide during run time that it is a presentation element (content) and that it is a code element. The Razor View Engine is compatible with a unit testing framework. The Razor template does not require the controller or webserver to host it, so views written in Razor are fully testable. The file extension of a Razor view is cshtml (for C#) and vbhtml (for VB.NET). By default all text from the @ expression is HTML encoded. Razor is not a new language. It is easy to learn. The main advantage of Razor, is that there is less transition between HTML and code because Razor provides an optimized syntax to generate HTML using a code focused templating approach.

Advantages of Razor View Engine

  • Easy to Learn: Razor is easy to learn. We can also use our existing HTML skills.
  • It is Compact, Expressive, and Fluid. Razor helps us to minimize the coding and provide us a fast and fluid coding work flow.
  • The parser (available with Razor) is smart enough. It is also able to decide at run time what is a code element and what is a content element.For example, in the following code the @ character is also part of an email address, but Razor is smart enough to identify which is code and which is static content.
           Please contact to abc@gmail.com to more information
           Current Date time : @DateTime.Now
    
  • Razor is not a new language but it is markup so that we can also use Razor with any language like C# and VB.
  • Razor also supports the concept of layout pages (the same as Master Pages in ASPX View Engine), that allows us to define a common site template, in other words a common look and feel across all the pages within a web site/application.
  • Razor does not require any special tool to write markup. We can also write our markup code with any old plain text editor like Notepad.
  • The Razor View Engine is designed such that it also supports unit test views without requiring a controller and web server. This can be hosted in any unit project. There is no special application domain required.
  • ASP.NET MVC has HTML helpers that are methods that can be invoked within a code block. All existing HTML extension methods can be used with a Razor View Engine without any code changes.
  • The code looks clean.
  • Powerful built-in validation of markup that helps us to avoid unwanted runtime exceptions due to errors in the view.
  • The Razor View Engine has the section concept that is equivalent to content placeholders in the ASPX View Engine and that can be optional.
  • The @model directive provides a cleaner and more concise way to define a strongly typed model.

One of the disadvantages of Razor is, it is not supported by visual editors like Dream Viewer.