Data Types in C#

C# is a language in which every variable and object should have a declared type.In this article we are going to discuss about datatypes in C#. Many dataypes in C# are from C and C++.

There are different ways of defining data types in C# let us see each of them in brief:-

1. If the data type is built-in it can be defined as as int or char.

2. If it is user-defined type one can define it as a class or as an interface.

3. Data types can also be defined as Value Types or Reference Types.

a. Value Types

This datatypes are used for storing values of the data.Value types have two main types

1. Structs

2. Enumerations

In structs types there are types like:

a. Integral types
b. Floating-point types
c. decimal
d. bool

In Integral type there are categories like

sbtype – Signed 8-bit integer
byte – Unsigned 8-bit integer
short – Signed 8-bit integer
ushort – Unsigned 16-bit integer
int – Signed 32-bit integer
uint – Unsigned 32-bit integer
long – Signed 64-bit integer
ulong – UnSigned 64-bit integer

In Floating-point types there are categories like
float - 7 digits
double – 15-16 digits

In decimal precise decimal type is with 28 significant digits.

In bool is used to declare variables to store the Boolean values, true and false .

b.Reference Types
This datatypes are used for storing references to the actual data.

Let us discuss both of them in detail

In Reference types there are types like object and string. Object datatype is the base type of all other types. In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. One can assign values of any type to variables of type object.

using System;
class SampleClass
{
public int r = 5;
}

class MainClass
{
static void Main()
{
object o;
o = 1; // an example of boxing
Console.WriteLine(o);
Console.WriteLine(o.GetType());
Console.WriteLine(o.ToString());

o = new SampleClass();
SampleClass classRef;
classRef = (SampleClass)o;
Console.WriteLine(classRef.r);
}
}

Output

1
System.Int32
1
5

String datatype is a sequence of unicode characters .This is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references which helps one to compare strings more easier.

using System;
class TestClass
{
static void Main()
{
string a = “Good “;
string b = “Morning”;
Console.WriteLine( a + b );
Console.WriteLine( a + b == “Good Morning” );
}
}

Output

Good Morning
True

If you enjoyed this post, make sure you subscribe to my RSS feed!

Leave a Reply