C# | Data Types
Last Updated :
18 Jun, 2020
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.
Data types in C# is mainly divided into three categories
- Value Data Types
- Reference Data Types
- Pointer Data Type
-
Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :
char: G
integer: 89
short: 56
long: 4564
float: 3.733064
double: 8.358674532
decimal: 389.5
Unsinged integer: 95
Unsinged short: 76
Unsinged long: 3624573
Example :
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
static void Main()
{
sbyte a = 126;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
}
}
}
|
Output :
126
127
-128
-127
Example :
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
static void Main()
{
byte a = 0;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
a = 254;
a++;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
}
}
}
|
Output :
0
1
255
0
-
Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.
Alias |
Type name |
Values |
bool |
System.Boolean |
True / False |
Example :
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
static void Main()
{
bool b = true ;
if (b == true )
Console.WriteLine( "Hi Geek" );
}
}
}
|
Output :
Hi Geek
- Reference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.
GeeksforGeeks
20
System.Int32
- Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.
To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
Syntax :
type* identifier;
Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid
Example :
using System;
namespace Pointerprogram {
class GFG {
static void Main()
{
unsafe
{
int n = 10;
int * p = &n;
Console.WriteLine( "Value :{0}" , n);
Console.WriteLine( "Address :{0}" , ( int )p);
}
}
}
}
|
Share your thoughts in the comments
Please Login to comment...