In C#, data types determine the kind of data that variables can hold. They are essential for specifying whether a variable can store integers, floating-point numbers, characters, or Boolean values. Data types also establish the memory size and the range of values that can be stored in memory.
Types of Data Types in C#
There are three categories of data types in C#. These include:
The styles defined for the data types diagram include a linear gradient background, rounded borders, padding, and a specific font family. The title of the diagram is centered with a specific color, font size, and weight, while the root of the tree structure has a different background color, text color, padding, and border radius. The branches of the tree are displayed using flexbox with spacing and wrapping properties. Each branch has a background color, padding, and minimum width. Labels for branches have specific styling with different background colors based on the type. Branch items are displayed in a column with spacing between them, each with a background, text color, padding, and font size.
Here, we will explore various data types individually.
Primitive Data Types
In C# programming language, primitive data types are essential, pre-defined types that denote basic values. These data types encompass various kinds of data, such as integer types, floating-point numbers, decimal type, character type, and boolean type.
| Data Type | Size |
|---|---|
int |
2-byte or 4-byte |
| float | 4-byte |
| double | 8 byte |
char |
8-bit / 1 byte |
| long int | 8-byte |
| long double | 12 byte |
| boolean | 1byte or 8bits |
| short int | 2 byte |
Here, we will discuss these primitive data types one by one.
1) Integer Types
In C#, the integer data type is employed to hold numerical values excluding decimals.
i. Signed integer: This data type is employed for storing integer values that can be either positive or negative. Typically, it occupies 4 bytes of memory. It is specifically designed to hold values within the range of -2,147,483,648 to 2,147,483,647.
Example:
signed int number = -50
ii. Unsigned Integer: The unsigned integer data type is utilized for storing non-negative integer values. It occupies 4 bytes of memory allocation and can hold values ranging from 0 to 4,294,967,295.
Example:
Unsigned int number = 50
iii. Short Integer: The short int data type is restricted to a limited range of values, from -32,768 to 32,767.
Example:
Short int number = 100;
iv. Long Integer: The long integer data type is primarily used for storing significant numerical values, occupying a memory space ranging from 4 to 8 bytes.
Example:
long int number a = 1000
C# Integer Types Example
Let's consider a scenario to demonstrate the integer data type in C#.
Example
using System;
class Program
{
static void Main()
{
int regularInt = 100; // regular signed 32-bit integer
uint unsignedInt = 200; // Unsigned 32-bit integer
short shortInt = -32000; // Signed 16-bit integer
long longInt = 9223372036854775807; // Signed 64-bit integer
Console.WriteLine("int: " + regularInt);
Console.WriteLine("uint: " + unsignedInt);
Console.WriteLine("short: " + shortInt);
Console.WriteLine("long: " + longInt);
}
}
Output:
int: 100
uint: 200
short: -32000
long: 9223372036854775807
Explanation:
In this instance, we've explored the signed, unsigned, short, and long integer data types. Following that, we employ the Console.WriteLine method to showcase the results.
2) Floating-Point Type
C# offers two primary floating-point data types for storing real numbers, encompassing fractions and decimals. These data types vary in precision and memory consumption, catering to a range of numerical calculations.
a. Floating point (32-bit): It occupies a memory space of 4 bytes and is commonly referred to as single precision.
Example:
float number = 32.4f;
The double data type, also known as double precision, requires 8 bytes of memory allocation. It offers a precision of 15-16 decimal digits.
Example:
double number = 5.222222220000000
C# Floating-Point Types Example
Let's consider an example to demonstrate the floating-point data types in C#.
Example
using System;
class Program
{
static void Main()
{
// floating-point data
float h1 = 5.9f;
// This is a double-point data
double h2 = 72.5;
// Define h3 explicitly
double h3 = 180.3;
// Showing the values
Console.WriteLine("h1 is " + h1 + " ft");
Console.WriteLine("h2 is " + h2 + " ft");
Console.WriteLine("h3 is " + h3 + " ft");
}
}
Output:
h1 is 5.9 ft
h2 is 72.5 ft
h3 is 180.3 ft
Explanation:
In this instance, three variables - h1, h2, and h3 - are declared for the float and double data types. Subsequently, the output is displayed using the Console.WriteLine method.
3) Character Type:
In C#, the character data type is employed to hold a single character. It necessitates 8 bits or 1-byte of storage space. These data types are capable of depicting any character from the ASCII or Unicode collection, encompassing digits, alphabets, symbols, and more.
Example:
char alphabet = 's';
C# Character Type Example
Let's consider a scenario to demonstrate the data type for characters in C#.
Example
using System;
public class program
{
public static void Main(string[] args)
{
char letter = 'A';
Console.WriteLine("The character is " + letter);
}
}
Output:
The character is A
Explanation:
In this instance, we are focusing on the letter data type. Subsequently, we employ the Console.WriteLine method to showcase the result.
4) Boolean type (bool):
In C#, the boolean data type is employed to store logical values, such as true or false. It plays a crucial role in conditional statements and decision-making processes, enabling efficient evaluation of logical expressions and conditions.
Example:
bool b = true;
bool d = false;
C# Boolean Type Example
Let's consider an example to demonstrate the Boolean data type in C#.
Example
using System;
public class program
{
public static void Main(string[] args)
{
bool isRaining = true;
Console.WriteLine("Is it raining? " + isRaining);
}
}
Output:
Is it raining? True
Explanation:
In this instance, we are utilizing the isRaining boolean data type, followed by the utilization of the Console.WriteLine method to showcase the result.
Derived Data Type
In C#, a derived data type refers to a data type crafted by the developer to enhance functionality and enable advanced data manipulation. Such functionalities support organized programming methodologies for effective data handling and optimized memory utilization. Derived data types encompass arrays, pointers, and references among others.
1) Arrays
In C#, an array represents a collection of elements of the same type stored in contiguous memory locations. Arrays aid in enhancing data manipulation efficiency by grouping multiple values under a single variable identifier.
i. One-dimensional array
In C#, a one-dimensional array is primarily used to store a sequential set of elements. It is also referred to as a linear array.
Example:
int number[3] = {10,20,30}
ii. Multi-dimensional array
A multi-dimensional array is employed to contain numerous arrays within arrays. It operates with rows and columns to store information in a matrix layout.
iii. Dynamic array
In C#, a dynamic array is created using the List<S> class, enabling the storage and manipulation of data at runtime.
Syntax
It has the following syntax:
List<int> newlist = new List<int>(arr);
C# Array Example
Let's explore some instances of one-dimensional arrays, multi-dimensional arrays, and dynamic arrays.
Example
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr1 = { 10, 20, 30, 40, 50 }; // one-dimensional array
Console.WriteLine("One-Dimensional Array:");
foreach (int item in arr1) // for each loop
{
Console.Write(item + " ");
}
Console.WriteLine("\n");
int[,] arr2 = { // multi-dimensional array
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
Console.WriteLine("Two-Dimensional Array:");
for (int i = 0; i < arr2.GetLength(0); i++) //nested for loop
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
Console.Write(arr2[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
List<string> arr3 = new List<string>(); // dynamic-array
arr3.Add("A");
arr3.Add("B");
arr3.Add("C");
Console.WriteLine("Dynamic Array:");
foreach (string alphabet in arr3) // foreach loop
{
Console.WriteLine(alphabet);
}
}
}
Output:
One-Dimensional Array:
10 20 30 40 50
Two-Dimensional Array:
1 2
3 4
5 6
Dynamic Array:
A
B
C
Explanation:
In this illustration, we showcase three varieties of arrays - a single-dimensional array, a two-dimensional array, and a resizable array implemented with List<T>. Initially, the integer array's elements are exhibited using a foreach loop. Following that, a two-dimensional array (also known as a matrix) is shown, with nested for loops utilized to access rows and columns. Lastly, a List<string> is employed as a dynamic array that can expand during program execution, and its contents are displayed using another foreach loop.
2) Pointer
In C#, pointers serve as a variable designed to hold the memory location of another variable. They are classified as a reference-type variable capable of storing the memory address of a different variable. Pointers offer efficiency as they allow for direct access and storage of memory addresses of other variables. The * symbol is used to denote pointers in C#.
Syntax
It has the following syntax:
type*var-name;
When working with pointers in C#, it is necessary to utilize the unsafe modifier. The syntax for declaring a pointer variable in C# is shown below:
int *sp; // integer type of pointer
double *dp; // double type of pointer
Here, the pointer variable declaration is outlined below.
Example
static unsafe void Main(string[] args) {
int num = 100;
int* p = &var;
Console.WriteLine("Number is: {0} ", num);
Console.WriteLine("Address is: {0}", (int)p);
Console.ReadKey();
}
3) Reference Type
In C#, a reference type is a duplicate of the reference (memory location) that gets transferred to the method. It serves as a synonym for any other variable.
C# Reference Type Example
Let's consider an example to demonstrate a reference type in C#.
Example
using System;
class Program
{
class P //declaring class P
{
public string Name;
}
static void Main()
{
P p1 = new P(); // p1 is the object of P
p1.Name = "John";
P p2 = p1; // p2 is the reference to the same object as p1
p2.Name = "Albert"; // modify the name by using p2
// both refer to the same object, p1.Name also changes
Console.WriteLine("p1.Name: " + p1.Name);
Console.WriteLine("p2.Name: " + p2.Name);
}
}
Output:
p1.Name: Albert
p2.Name: Albert
Explanation:
In this instance, we define a class called P, within which a variable of type string is declared. Subsequently, an instance of the class, p1, is instantiated in the main function and a value is assigned to it. Following this, another object, p2, of the class P is created, and a different name is assigned to it. Ultimately, the output is displayed using Console.WriteLine.
User-defined data type
In C#, programmers typically craft user-defined data types to meet specific requirements. These custom data types play a crucial role in efficiently structuring and handling real-world objects.
Types of User-Defined Data Types:
There are several types of user-defined data types in C# as follows:
- Struct
- Class
- Union
- Enumeration
Here, we will explore each of these custom data types individually in the C# programming language.
1) Struct
In C#, a struct is a custom-defined data type that enables the storage of multiple variables of different data types.
Syntax
It has the following syntax:
struct StructName {
datatype member;
};
C# Struct Example
Let's consider an example to demonstrate the struct data type in C#.
Example
using System;
namespace Program
{
struct detail //define the struct
{
public int num;
public string performance;
}
class Program
{
static void Main()
{
detail p; // create the struct
p.num = 10;
p.performance = "Excellent";
Console.WriteLine($"Num: {p.num}, Performance: {p.performance}");
}
}
}
Output:
Num: 10, Performance: Excellent
Explanation:
In this instance, we define a struct data type with the struct keyword to hold both integer and string values. Subsequently, we initialize a variable "p" with values of integer and string types. Lastly, the output is displayed using the Console.WriteLine method.
2) Class
In C#, a class represents a group of data members and methods. This concept is predominantly employed in Object-Oriented Programming (OOP) languages. The declaration of a class is done by using the class keyword.
Syntax
It has the following syntax:
Class classname
{
// data member
// data method
}
C# Class Example
Let's consider an instance to demonstrate the Class concept in C#.
Example
using System;
namespace Example
{
class Vehicle // create a class
{
string car = "Innova";
public void DisplayCar()
{
Console.WriteLine(car);
}
}
class Program
{
static void Main(string[] args)
{
Vehicle myObj = new Vehicle();
myObj.DisplayCar();
}
}
}
Output:
Innova
Explanation:
In this instance, a class titled Vehicle is initialized. The DisplayCar function is defined to set the car values. Subsequently, an object named myObj is instantiated from the Vehicle class, followed by invoking the method (DisplayCar) within the primary function.
3) Union
In C#, a union refers to a custom data type that enables the consolidation of multiple data elements within a singular entity, like a structure.
Syntax
It has the following syntax:
union UnionName {
dataType1 member1;
dataType2 member2;
...
};
C# Union Example
Let's consider an example to demonstrate the concept of Union in C#.
Example
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public int Value;
[FieldOffset(0)]
public float FloatValue;
}
class Program
{
static void Main()
{
Union u = new Union();
u.Value = 42;
Console.WriteLine("Int: " + u.Value);
Console.WriteLine("Float: " + u.FloatValue);
}
}
Output:
int: 42
Float: 5.885454E-44
Explanation:
In this instance, we store integer and floating-point values within a union, allowing it to contain only one value at a time. The primary function showcases how a union replaces previous data when a new value is assigned by consecutively assigning various values to the union variable u. Ultimately, the output is displayed using the Console.WriteLine method.
4) Enumeration
In C#, enumeration represents a custom data type enabling storage of a set of fixed values. This is achieved by employing the enum keyword, which enhances code clarity and ease of maintenance.
Syntax
It has the following syntax.
enum enum_variable{
// string
//string
…
}
C# Enumeration Example
Let's consider a scenario to demonstrate the Enumeration data type in C#.
Example
using System;
class Program
{
enum DaysOfWeek // create the enum for days of week.
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
static void Main()
{
DaysOfWeek today = DaysOfWeek.Wednesday;
Console.WriteLine("Today is " + today);
}
}
Output:
Today is Wednesday
Explanation:
In this instance, we define the enumeration for the weekdays. Following that, the primary function initializes and sets the variable, setting Wednesday as the value for today. Subsequently, the output is displayed using the Console.WriteLine method.
Conclusion:
In summary, the C# data type plays a crucial role for developers when building software applications. It serves as the primary focus during development, determining the kind of data a variable can hold. Additionally, it specifies the memory size and range allocated for storing data.
C# Data Type FAQs
1) What is the data type?
The data type specifies the kind of data that a variable can hold, determining its memory allocation and allowable value range.
2) What is the Primitive data type in C#?
The primitive data type is a category of data types that are inherently supported by the compiler. They are commonly referred to as built-in data types.
Ex- int, float, char, string etc.
The primary classifications of data types in C# include:
- Value types
- Reference types
- Pointer types
In C#, there are three main categories of data type.
- Primitive data type
- Derived data type
- User-defined data type
4) What is a string data type in C#?
In C#, the string data type represents a sequence of characters.
For example,
string s = "Hello-World";
5) What is the Boolean data type?
In C#, a boolean data type is employed to symbolize the logical states of True or False.