C# Data Types

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Data Types in C#

Data types are fundamental to programming in any language, determining the kind of values variables can hold and the operations applicable to them. In C#, it’s essential to declare the type of a variable beforehand, enhancing code reliability and readability.

Value Types and Reference Types

C# classifies data types into two categories: value types and reference types.

▪ Value types: store data directly in their memory allocation. Examples include int, float, bool, char, enum, and struct.

Example

int value1 = 10;

int value2 = value1; // value2 gets a copy of value1

value2 = 20; // Changing value2 doesn’t affect value1

Console.WriteLine(“Value1: ” + value1); // Output: 10

Console.WriteLine(“Value2: ” + value2); // Output: 20

▪ Reference types: store references to memory locations containing the actual data. Examples comprise object, string, class, interface, delegate, and array.

Example

int[] array1 = { 1, 2, 3 };

int[] array2 = array1; // array2 points to the same memory location as array1

array2[0] = 5; // Modifying array2 also modifies array1

Console.WriteLine(“Array1[0]: ” + array1[0]); // Output: 5

Console.WriteLine(“Array2[0]: ” + array2[0]); // Output: 5

Predefined Data Types

C# provides predefined data types, also termed built-in or simple data types, categorized as follows:

Numeric types: Used for storing numbers, such as int, long, byte, float, double, decimal, etc.

Boolean type: Stores true or false values.

Character type: Stores single Unicode characters.

String type: Stores sequences of Unicode characters.

Below is a summary of predefined data types, including their sizes, ranges, and suffixes:

Examples of Predefined Data Types

Below are examples demonstrating the declaration and initialization of variables with different predefined data types:

int age = 25;

float temperature = 98.6f;

char grade = ‘A’;

bool isRaining = true;

string name = “John”;

User-Defined Data Types

Numeric Types: Used for storing numeric values, encompassing both integer types (such as int, long, byte) and floating-point types (such as float, double, decimal).

Boolean Type: Represents logical true or false values, denoted by the bool keyword.

Character Type: Stores single Unicode characters, represented by the char keyword.

String Type: Stores sequences of Unicode characters, denoted by the string keyword.

Example of User-defined Data Types

public class Person {

    public string Name { get; set; } // Property to store person’s name

    public int Age { get; set; } // Property to store person’s age

}

Person person1 = new Person();

person1.Name = “Alice”;

person1.Age = 30;

Console.WriteLine($”Name: {person1.Name}, Age: {person1.Age}”);

Course Video