Showing posts with label DataType. Show all posts
Showing posts with label DataType. Show all posts

Difference between String and string data types

There is no difference between string and String data type. string is C# based keyword and it is alaises for CLR Type(String).

C# defines a number of aliases for CLR types. It have the keywords because they are easier to remember and programmers coming from other languages like c/c++ would also be familiar with these types. They may be used interchangably, and even mixed together,
e.g : string x = new System.String(' ', 5);

These are the aliases defined:

string->System.Strings
byte->System.SByte
byte->System.Byte
short->System.Int16
ushort->System.UInt16
int->System.Int32
uint->System.UInt32
long->System.Int64
ulong->System.UInt64
char->System.Char
float->System.Single
double->System.Double
bool->System.Boolean
decimal->System.Decimal

Boxing and Unboxing in .NET

Boxing:
Converting a value type to reference type is called Boxing.

Unboxing:
Unboxing is an explicit operation. You have to tell which value type you want to extract from the object.

Int32 vt= 10; //value type variable
object rt= vt; /*memory is allocated on the heap of size equal to size of vt,the value type bits are copied to the newly allocated memory and the address of the object is returned and stored in rt.This is basically called Boxing.*/

Int32 vt2=(Int32)rt;//Unboxing

Purpose of Boxing and UnBoxing :

.NET provides a unified type system. All types including value types derive from the type object. It is possible to call object methods on any value, even values of primitive types such as int.

private void display()
{
Console.WriteLine(3.ToString());
}

calls the object-defined ToString method on an integer value.In programs that need int values to behave like objects, this capability is available on demand. This ability to treat value types as objects bridges the gap between value types and reference types that exists in most languages.