C# And Its Types


INTRODUCTION

In learning a new language the first pace isusually to learn basic concepts such asvariables,operators,types,expressions etc.Variables represent storage locations. Every variable has a type thatdetermines what values can be stored in the variable. C# is a stronglytype-safe language, and the C# compiler assurance that values stored invariables are always of the suitable type.In this article let us seeabout the types in C#.

Types

The types of the C# language are divided into three categories: Value types,reference types, and pointer types.

** Value types include simple types (e.g., char, int, and float), enum types, and struct types.

** Reference types include class types, interface types, delegate types, and array types.

** Pointer types can be used only in unsafe code.

Value types differ from reference types inthat variables of the value types directly contain their data, whereasvariables of the reference types store references to objects. Withreference types, it is possible for two variables to reference the sameobject, and thus possible for operations on one variable to affect theobject referenced by the other variable. With value types, thevariables each have their own copy of the data, and it is not possiblefor operations on one to affect the other.

The example

using System;
class type
{
public int Value = 0;
}
class Test
{
static void Main() {
int val1 = 0;
int val2 = val1;
val2 = 123;
type ref1 = new type();
type ref2 = ref1;
ref2.Value = 123;
Console.WriteLine("Values: {0}, {1}", val1, val2);
Console.WriteLine("References: {0}, {1}", ref1.Value, ref2.Value);
}
}

shows this difference. The output of the program is
Values: 0, 123
Refs: 123, 123
Theassignment to the local variable val1 does not impact the localvariable val2 because both local variables are of a value type (thetype int) and each local variable of a value type has its own storage.In contrast, the assignment ref2.Value = 123; affects the object thatboth ref1 and ref2 reference.

Value Types:

A variable representing an object of value type contains the object itself.(It does not contain a pointer to the object).
The value types of C# can be grouped as follows:

Simple Types:

Integral Types(sbyte,byte,short,ushort,int,uint,long,ulong) ,bool type, chartype,Floating point types(flaot,double) and the decimal types.They areall aliases of the .NET System Types.

System.Int32 a= 10; //It is a value type

The following table shows the integral types, their size, and range.

 

Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 147483648 to 2147483647
uint 32 0 to 4294967295
long 64 -9223372036854775808 to 9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535

Boolean types

The boolean values are written to the consoleas a part of a sentence. The "bool" type is simply either a true orfalse.It`s size is 1 bit.

Boolean.cs

using System;

class Booleans {

public static void Main() {
bool content = true;
bool noContent = false;

Console.WriteLine("It is {0} that this article is useful.", content);
Console.WriteLine("The statement above is not {0}.", noContent);
}
}

When run, this program produces the following output:

>It is True that this article is useful.
>The statement above is not False.

char type

The char type is used to represent Unicode characters. A variable of type char represents a single 16-bit Unicode character.
There are no implicit conversions from char to other data types available.That means treating a char variable just as another integral data type is not possible.

Floating point types

C# supports two floating point types: float and double.

The float and double types are represented using the 32-bit single-precision and 64-bit double-precision.

The decimal type is appropriate forcalculations in which rounding errors caused by floating pointrepresentations are unacceptable. Common examples include financialcalculations such as tax computations and currency conversions. Thedecimal type provides 28 significant digits.

Floating point types are used when you need to perform operations requiring fractional representations.

Type Size(in bits) Precision Range
float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308
decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028

Struct Types

A struct type is a value type that can declareconstructors, constants, fields, methods, properties, indexers,operators, and nested types.By using struct one can create lightweight objects.As class objects noadditional refrences are created in structs so we can conserve memeory.

The example

using System;
struct Data {
public byte b1,b2;
}

class test {
public static void Main() {
Data myData;
myData.b1=111;
myData.b2=1;
Console.Write("{0}.{1}.",myData.b1,myData.b2);
}

}

Enumeration Types

An enumeration type is a distinct type withnamed constants. Every enumeration type has an underlying type, whichcan be either byte, short, int, or long. Enumeration types are definedthrough enumeration declarations An enum type declaration defines atype name for a related group of symbolic constants. The body of anenum type declaration defines zero or more enum members, which are thenamed constants of the enum type. No two enum members can have the samename. An enum declaration can not contain declarations of methods,properties, events, operators, or types.

The associated value of an enum member isassigned either implicitly or explicitly. If the declaration of theenum member has a constant-expression initializer, the value of thatconstant expression, implicitly converted to the underlying type of theenum, is the associated value of the enum member.

If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows:
� If the enum member is the first enum member declared in the enum type, its associated value is zero.
� Otherwise, the associated value of the enum member is obtained byincreasing the associated value of the previous enum member by one.This increased value must be within the range of valu
es that can berepresented by the underlying type.

The example

 

using System;
enum Color
{
Red,
Green = 10,
Blue
}
class Test
{
static void Main() {
Console.WriteLine(StringFromColor(Color.Red));
Console.WriteLine(StringFromColor(Color.Green));
Console.WriteLine(StringFromColor(Color.Blue));
}
static string StringFromColor(Color c) {
switch (c) {
case Color.Red:
return String.Format("Red = {0}", (int) c);
case Color.Green:
return String.Format("Green = {0}", (int) c);
case Color.Blue:
return String.Format("Blue = {0}", (int) c);
default:
return "Invalid color";
}
}
}

prints out the enum member names and their associated values. The output is:
Red = 0
Blue = 10
Green = 11

For the following reasons:
� the enum member Red is automatically assigned the value zero (since it has no initializer and is the first enum member);
� the enum member Blue is explicitly given the value 10;
� and the enum member Green is automatically assigned the value one greater than the member that textually precedes it.

Reference Types:

A variable representing an object of Referencetype contains reference or address of the actual data.Reference typesare allocated on the managed heap.Different reference types are

The Object Type
The class Type
Interfaces
Delegates
The string type
Arrays

The object type

The object class type is the ultimate baseclass of all other types.Because it is the base class for allobjects,you can assign values of any type to it. Every type in C#directly or indirectly derives from the object class type.It is notequivalent to void* as in C++.The object type is used when a value type is boxed.

Class types

A class type defines a data structure thatcontains data members (constants, fields, and events), function members(methods, properties, indexers, operators, constructors, anddestructors), and nested types. Class types support inheritance, amechanism whereby derived classes can extend and specialize baseclasses.Only single inheritance is allowed.However a class in C# canderive from multiple interfaces.

The string type

The string type is a sealed class type thatinherits directly from object. Instances of the string class representUnicode character strings.Values of the string type can be written as string literals C# has basetype string for manipulating string data.

Its usage is simple

string author="arun ganesh";

Even we can access a single character with the help of accessing the indexer.char first=author[0];

Interface types

An interface declares a refrence type that hasabstract members only.Only the signature exists ,but there is noimplementation code at all.An implementation of this is that we cannotinstantiate an interface,only an object that derives from theinterface.

The example

interface Inter
{
void showInter();
}

As I said we cannot instantiate an object fromthis definition,but we can derive a class from it.However, that classmust implement the showinter abstract method.The main differencebetween interface members and class members is that interface membersdo not have an implementation.

class Ainter:Inter
{
public void showInter()
{
Console.WriteLine("IMPLEMENTATION");
}
}

Array types

An array is a data structure that contains anumber of variables which are accessed through computed indices. Thevariables contained in an array, also called the elements of the array,are all of the same type, and this type is called the element type ofthe array.

The example

using System;

class Array {

public static void Main() {
int[] Ints = { 25, 9, 79 };
string[] myStr = new string[4];

Console.WriteLine("Ints[0]: {0}, Ints[1]: {1}, Ints[2]: {2}",
Ints[0], Ints[1],Ints[2]);

myStr[0] = "gnana arun ganesh";
myStr[1] = "gnanavel";
myStr[2] = "vadi";
myStr[3] = "saru";

Console.WriteLine("myStr[0]: {0}, myStr[1]: {1}, myStr[2]:{2},
myStr[3]: {3}",myStr[0], myStr[1], myStr[2]),mystr[3]);

}
}

Delegate types

A delegate is a data structure that refers toa static method or to an object instance and an instance method of thatobject.A delegate encapsulate a method with a certain signature. Theclosest equivalent of a delegate in C or C++ is a function pointer, butwhereas a function pointer can only reference static functions, adelegate can reference both static and instance methods. In the lattercase, the delegate stores not only a reference to the method�s entrypoint, but also a reference to the object instance for which to invokethe method.

Unlike function pointers, delegates areobject-oriented, type-safe, and secure. Delegates are reference typesthat derive from a common base class: System.Delegate. A delegateinstance encapsulates a method � a callable entity. For instancemethods, a callable entity consists of an instance and a method on theinstance. If you have a delegate instance and an appropriate set ofarguments, you can invoke the delegate with the arguments. Aninteresting and useful property of a delegate is that it does not knowor care about the class of the object that it references. Any objectwill do; all that matters is that the method�s signature matches thedelegate�s. This makes delegates perfectly suited for "anonymous"invocation. This is a powerful capability.

There are three steps in defining and usingdelegates: declaration, instantiation, and invocation. Delegates aredeclared using delegate declaration syntax. A delegate that takes noarguments and returns void can be declared with

delegate void SimpleDelegate();

A delegate instance can be instantiated usingthe new keyword, and referencing either an instance or class methodthat conforms to the signature specified by the delegate. Once adelegate has been instantiated, it can be called using method callsyntax.

The example

class Test
{
static void A() {
System.Console.WriteLine("Test.A");
}
static void Main() {
SimpleDelegate d = new SimpleDelegate(A);
d();
}
}

A SimpleDelegate instance is created and thenimmediately invoked.Of course, there is not much point in instantiating a delegate for amethod and then immediately calling via the delegate, as it would besimpler to call the method directly. Delegates show their usefulnesswhen their anonymity is used. For example, we could define a MultiCallmethod that can call repeatedly call a SimpleDelegate.

void Mult
iCall(SimpleDelegate d, int count) {
for (int i = 0; i < count; i++)
d();
}
}

Summary

C# is a strongly type-safe programminglanguage.Thus all operations on variable areperformed with consideration of what the variable`s type is .Thus thisarticle concentrates on a lot of important information about the C#types.

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!