|
Data Types in C# |
|
|
|
Signed
Unsigned
Others
The following is a simple program in which we have initialized an int, a float, a char and a bool variable. Next we displayed the values and types of the variables. using System ; static void Main ( string [ ] args ) int i = 20 ; } } The typeof operator is used to obtain the System.Type object for a type.
All the value types are nothing but simple types. Simple types are nothing but predefined structures. The simple types are identified through reserved keywords, but these reserved words are simply aliases for the predefined structures in the System namespace. For eg int (keyword) is nothing but an alias for System.Int32 structure. C# also supports user defined structures like any other language does. Structures are prefaced with the keyword struct. Because a simple type aliases a structure, every simple type has members. For example, int has the members declared in System.Int32 and the members inherited from System.Object, because this structure inherits from System.Object, and the following statements are permitted.
int n = 10 ;
Here, ToString( ) function of object class gets called. We cannot inherit from these structures and they are sealed. For that matter everything is derived from the object class
In C++ primitive data types were simple variables not objects. C++ did not provide any way to convert the variables into objects. C# uses a third way. In C#, the primitive types are treated as objects
as and when necessary. For using the value type variable as an object we are not required to use wrapper classes. C#’s type system is
unified such that value of any type can be treated as an
object. We can convert any value type to reference type and vice versa using boxing and unboxing. This is discussed later. Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types.
All value types implicitly declare a public
parameterless constructor called the default constructor. The default constructor returns a zero-initialized instance known as the default value for the value type. Following are the default values for simple type, and struct-type
Like any other constructor, the default constructor of a value type is invoked using the new operator. Because every value type implicitly has a public parameterless constructor, it is not possible for a struct type to contain an explicit declaration of a parameterless constructor. A struct type is however permitted to declare parameterized constructors. |