C# Examples

C# Example Code


C# Data Types

In C#, data types are core fundamental elements which makes C# strongly typed language. This means all operation are typed checked by the compiler for type competibility. Because C# is strongly typed language, you required to tell to the compiler which data type you are using in programming. Both reference and value types are derived from the ultimate base class object.

C# has its own set of built in data types, which can be categories into value type and reference type. In C# 4 they introduced new data type called dynamic. Value type are used to hold actual value such as 3.44 or 2884, but reference type hold reference to the value. The most commonly used reference types are string or class data type.

Each data type in C# has corresponding underlying .NET Common Language Runtime type. For example, the int type in C# maps to the System.Int32 type in the runtime.

C# has following data types

  • Value Type
  • Reference Type

C# Value Types

Value type also known as simple type or primitive types which include boolean, byte etc. C# specifies specific range for each value type for example byte value type can hold value range from 0 to 255. All value types are derived implicitly from the System.ValueType.

C# has a set of predefined value types.

Data TypeMeaningAlias ForAllowed Value
boolBoolean valueSystem.BooleanTrue or False
byte8-bit unsigned integerSystem.Byte0 to 255
char16-bit Unicode characterSystem.CharU +0000 to U +ffff
decimal128-bit precise decimal values with 28-29 significant digitsSystem.Decimal(-7.9 x 1028 to 7.9 x 1028) / 100 to 28
double64-bit double-precision floating point typeSystem.Double(+/-)5.0 x 10-324 to (+/-)1.7 x 10308
float32-bit single-precision floating point typeSystem.Single-3.4 x 1038 to + 3.4 x 1038
int32-bit signed integer typeSystem.Int32-2,147,483,648 to 2,147,483,647
long64-bit signed integer typeSystem.Int64-923,372,036,854,775,808 to 9,223,372,036,854,775,807
sbyte8-bit signed integer typeSystem.Sbyte-128 to 127
short16-bit signed integer typeSystem.Int16-32,768 to 32,767
uint32-bit unsigned integer typeSystem.UInt320 to 4,294,967,295
ulong64-bit unsigned integer typeSystem.UInt640 to 18,446,744,073,709,551,615
ushort16-bit unsigned integer typeSystem.UInt160 to 65,535

C# Value Type Example

using System;
class DataTypeDemo
{
	static void main()
	{
		int var1_int // integer variables;
		var1_int = 232332;
		
		bool var1_bool // boolean variables;
		var1_bool = true;
		
		bool var1_char // char variables;
		var1_char = 'v';
	}
}

C# Reference Types

In C#, reference type hold the address of value instead of directly to a value. The reference type is store in heap and does not have fixed size, for example string can be size form 2 bytes to all the memory available on a system. Reference types include string, class, interfaces and delegates. C# has built-in reference types as: object, dynamic, and string.