C# - Data Types and Variables

C# Data Types and Variables - Complete Tutorial

C#  Data Types and Variables

Understanding data types and variables in C# is fundamental to writing efficient and correct C# programs. This tutorial covers the complete range of data types, how variables are declared, value and reference types, nullable types, and best practices for choosing the right data type.

Introduction to Data Types in C#

In C#, a data type defines the type of data a variable can hold. It is a statically typed language, meaning the type of variable must be known at compile time. C# data types are categorized mainly into two groups:

  • Value Types
  • Reference Types

Value Types in C#

Value types store the actual data in memory. They are allocated on the stack and are faster in access. When a value type is assigned to another, the data is copied.

Common Value Types

  • Integral types: byte, short, int, long
  • Floating-point types: float, double
  • Decimal type: decimal
  • Boolean type: bool
  • Character type: char
  • Structs and Enums

Examples of Value Types


// Integer type
int age = 30;

// Float type
float temperature = 36.6f;

// Boolean type
bool isActive = true;

// Character type
char grade = 'A';

Reference Types in C#

Reference types store the reference to the memory location, not the actual data. They are allocated on the heap and can be more complex structures like objects, arrays, and strings.

Common Reference Types

  • String
  • Array
  • Class
  • Interface
  • Delegate
  • Dynamic
  • Object

Example of Reference Types


// String is a reference type
string name = "John Doe";

// Object is base class for all types
object obj = 45;

// Array is also a reference type
int[] scores = { 85, 90, 95 };

Declaring Variables in C#

Variables are containers for storing data values. In C#, you must declare a variable before using it. The syntax is:

dataType variableName = value;

Examples:

int count = 10;
double salary = 45000.75;
string city = "New York";

Implicitly Typed Variables with var

The var keyword lets the compiler infer the data type based on the value. It must be initialized at the time of declaration.

var result = 100;       // inferred as int
var message = "Hello";  // inferred as string

C# Built-in Data Types

Integral Data Types

byte    // 0 to 255
sbyte   // -128 to 127
short   // -32,768 to 32,767
ushort  // 0 to 65,535
int     // -2,147,483,648 to 2,147,483,647
uint    // 0 to 4,294,967,295
long    // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong   // 0 to 18,446,744,073,709,551,615

Floating-Point Types

float   // 6-9 digits precision
double  // 15-17 digits precision
decimal // 28-29 digits precision (used in financial calculations)

Other Types

char    // A single Unicode character
bool    // true or false
string  // sequence of characters
object  // base type of all types in .NET

Understanding Nullable Types

Value types cannot hold null by default. But by using nullable types (indicated by `?`), you can assign null to value types.

int? age = null;

if (age.HasValue) {
    Console.WriteLine("Age: " + age.Value);
} else {
    Console.WriteLine("Age not specified.");
}

Default Values of Data Types

Each data type in C# has a default value:

int defaultInt = default(int);     // 0
bool defaultBool = default(bool); // false
object defaultObj = default(object); // null

Constants and ReadOnly Variables

const Keyword

Constants are immutable values known at compile-time.

const double PI = 3.14159;

readonly Keyword

Readonly variables can be assigned only in constructor or declaration. They are evaluated at runtime.

readonly int creationYear = 2025;

Dynamic Type in C#

The dynamic type allows operations to bypass compile-time type checking. Type is resolved at runtime.

dynamic data = 100;
Console.WriteLine(data);
data = "C# Programming";
Console.WriteLine(data);

Boxing and Unboxing in C#

Boxing is converting a value type to object. Unboxing is retrieving value from object.

// Boxing
int num = 123;
object obj = num;

// Unboxing
int unboxed = (int)obj;

Variable Scope in C#

Local Variables

Declared inside a method and accessible only within it.

void Display() {
    int temp = 10;
    Console.WriteLine(temp);
}

Global Variables (Fields)

Declared within class but outside methods. Accessible within the class.

class Sample {
    int count = 5;

    void Show() {
        Console.WriteLine(count);
    }
}

Type Conversion in C#

Implicit Conversion

int x = 100;
long y = x;  // No data loss

Explicit Conversion (Casting)

double pi = 3.14;
int intPi = (int)pi; // Data loss possible

Using Convert Class

string numStr = "123";
int number = Convert.ToInt32(numStr);

Type Inference and var vs dynamic

var is type-safe and resolved at compile time, while dynamic is resolved at runtime.

var x = 10;          // int
dynamic y = 10;     // dynamic, can change type
y = "Now string";   // no error

Mastering C# data types and variables is essential for every C# developer. This tutorial gave you a comprehensive understanding of different data types, how they behave, and how to effectively declare and use variables. Whether you’re building a console app or enterprise solution, choosing the right data type improves performance, memory usage, and code clarity.


Beginner 5 Hours
C# Data Types and Variables - Complete Tutorial

C#  Data Types and Variables

Understanding data types and variables in C# is fundamental to writing efficient and correct C# programs. This tutorial covers the complete range of data types, how variables are declared, value and reference types, nullable types, and best practices for choosing the right data type.

Introduction to Data Types in C#

In C#, a data type defines the type of data a variable can hold. It is a statically typed language, meaning the type of variable must be known at compile time. C# data types are categorized mainly into two groups:

  • Value Types
  • Reference Types

Value Types in C#

Value types store the actual data in memory. They are allocated on the stack and are faster in access. When a value type is assigned to another, the data is copied.

Common Value Types

  • Integral types: byte, short, int, long
  • Floating-point types: float, double
  • Decimal type: decimal
  • Boolean type: bool
  • Character type: char
  • Structs and Enums

Examples of Value Types

// Integer type int age = 30; // Float type float temperature = 36.6f; // Boolean type bool isActive = true; // Character type char grade = 'A';

Reference Types in C#

Reference types store the reference to the memory location, not the actual data. They are allocated on the heap and can be more complex structures like objects, arrays, and strings.

Common Reference Types

  • String
  • Array
  • Class
  • Interface
  • Delegate
  • Dynamic
  • Object

Example of Reference Types

// String is a reference type string name = "John Doe"; // Object is base class for all types object obj = 45; // Array is also a reference type int[] scores = { 85, 90, 95 };

Declaring Variables in C#

Variables are containers for storing data values. In C#, you must declare a variable before using it. The syntax is:

dataType variableName = value;

Examples:

int count = 10; double salary = 45000.75; string city = "New York";

Implicitly Typed Variables with var

The var keyword lets the compiler infer the data type based on the value. It must be initialized at the time of declaration.

var result = 100; // inferred as int var message = "Hello"; // inferred as string

C# Built-in Data Types

Integral Data Types

byte // 0 to 255 sbyte // -128 to 127 short // -32,768 to 32,767 ushort // 0 to 65,535 int // -2,147,483,648 to 2,147,483,647 uint // 0 to 4,294,967,295 long // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 ulong // 0 to 18,446,744,073,709,551,615

Floating-Point Types

float // 6-9 digits precision double // 15-17 digits precision decimal // 28-29 digits precision (used in financial calculations)

Other Types

char // A single Unicode character bool // true or false string // sequence of characters object // base type of all types in .NET

Understanding Nullable Types

Value types cannot hold null by default. But by using nullable types (indicated by `?`), you can assign null to value types.

int? age = null; if (age.HasValue) { Console.WriteLine("Age: " + age.Value); } else { Console.WriteLine("Age not specified."); }

Default Values of Data Types

Each data type in C# has a default value:

int defaultInt = default(int); // 0 bool defaultBool = default(bool); // false object defaultObj = default(object); // null

Constants and ReadOnly Variables

const Keyword

Constants are immutable values known at compile-time.

const double PI = 3.14159;

readonly Keyword

Readonly variables can be assigned only in constructor or declaration. They are evaluated at runtime.

readonly int creationYear = 2025;

Dynamic Type in C#

The dynamic type allows operations to bypass compile-time type checking. Type is resolved at runtime.

dynamic data = 100; Console.WriteLine(data); data = "C# Programming"; Console.WriteLine(data);

Boxing and Unboxing in C#

Boxing is converting a value type to object. Unboxing is retrieving value from object.

// Boxing int num = 123; object obj = num; // Unboxing int unboxed = (int)obj;

Variable Scope in C#

Local Variables

Declared inside a method and accessible only within it.

void Display() { int temp = 10; Console.WriteLine(temp); }

Global Variables (Fields)

Declared within class but outside methods. Accessible within the class.

class Sample { int count = 5; void Show() { Console.WriteLine(count); } }

Type Conversion in C#

Implicit Conversion

int x = 100; long y = x; // No data loss

Explicit Conversion (Casting)

double pi = 3.14; int intPi = (int)pi; // Data loss possible

Using Convert Class

string numStr = "123"; int number = Convert.ToInt32(numStr);

Type Inference and var vs dynamic

var is type-safe and resolved at compile time, while dynamic is resolved at runtime.

var x = 10; // int dynamic y = 10; // dynamic, can change type y = "Now string"; // no error

Mastering C# data types and variables is essential for every C# developer. This tutorial gave you a comprehensive understanding of different data types, how they behave, and how to effectively declare and use variables. Whether you’re building a console app or enterprise solution, choosing the right data type improves performance, memory usage, and code clarity.


Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved