Variables and Data Types
Learn about C# variables, data types, and how to work with data
Variables
Variables are containers for storing data values. In C#, you must declare a variable before using it, specifying its data type.
Variable Declaration
// Syntax: dataType variableName = value;
int age = 25;
string name = "John Doe";
double price = 99.99;
bool isActive = true;Variable Naming Rules
Variables must follow these naming conventions:
// Valid variable names
int studentAge;
string firstName;
double _privateValue;
bool isReady2Go;
// Invalid variable names (will cause compilation errors)
// int 2students; // Cannot start with a number
// string first-name; // Cannot contain hyphens
// bool class; // Cannot use reserved keywordsBasic Data Types
C# provides several built-in data types for different kinds of data:
Numeric Types
// Integer types
int wholeNumber = 42; // 32-bit signed integer
long bigNumber = 1234567890L; // 64-bit signed integer
short smallNumber = 100; // 16-bit signed integer
byte tinyNumber = 255; // 8-bit unsigned integer
// Floating-point types
float singlePrecision = 3.14f; // 32-bit floating point
double doublePrecision = 3.14159; // 64-bit floating point (default)
decimal highPrecision = 99.99m; // 128-bit decimal (for financial calculations)
// Display the values
Console.WriteLine($"Integer: {wholeNumber}");
Console.WriteLine($"Double: {doublePrecision}");
Console.WriteLine($"Decimal: {highPrecision}");Character and String Types
// Character type (single character)
char grade = 'A';
char symbol = '#';
// String type (sequence of characters)
string message = "Hello, C#!";
string multiLine = @"This is a
multi-line
string using verbatim syntax";
// String interpolation
string firstName = "Alice";
int age = 30;
string greeting = $"Hello, my name is {firstName} and I'm {age} years old.";
Console.WriteLine(greeting);Boolean Type
// Boolean type (true or false)
bool isLoggedIn = true;
bool hasPermission = false;
// Boolean expressions
bool isAdult = age >= 18;
bool canVote = isAdult && isLoggedIn;
Console.WriteLine($"Can vote: {canVote}");Type Inference with var
C# allows automatic type inference using the var keyword:
// The compiler automatically determines the type
var number = 42; // Inferred as int
var text = "Hello"; // Inferred as string
var price = 19.99; // Inferred as double
var isReady = true; // Inferred as bool
// You can still see the inferred type in your IDE
Console.WriteLine(number.GetType()); // System.Int32
Console.WriteLine(text.GetType()); // System.StringNote: var can only be used when the compiler can infer the type from the initial assignment.
Constants
Constants are immutable values that cannot be changed after declaration:
// Using the const keyword
const double PI = 3.14159;
const string COMPANY_NAME = "TechCorp";
const int MAX_USERS = 1000;
// Using readonly (can be assigned in constructor)
readonly DateTime creationDate = DateTime.Now;
Console.WriteLine($"Pi value: {PI}");
Console.WriteLine($"Company: {COMPANY_NAME}");Type Conversion
C# supports both implicit and explicit type conversion:
Implicit Conversion
// Automatic conversion (no data loss)
int smallNumber = 100;
long bigNumber = smallNumber; // int to long (safe)
double decimalNumber = smallNumber; // int to double (safe)
Console.WriteLine($"Long: {bigNumber}, Double: {decimalNumber}");Explicit Conversion (Casting)
// Manual conversion (potential data loss)
double pi = 3.14159;
int wholePi = (int)pi; // Truncates decimal part
Console.WriteLine($"Original: {pi}, Truncated: {wholePi}");
// Using Convert class
string numberText = "123";
int convertedNumber = Convert.ToInt32(numberText);
bool convertedBool = Convert.ToBoolean("true");
Console.WriteLine($"Converted number: {convertedNumber}");
Console.WriteLine($"Converted boolean: {convertedBool}");Safe Conversion with TryParse
// Safe conversion that doesn't throw exceptions
string userInput = "not a number";
if (int.TryParse(userInput, out int result))
{
Console.WriteLine($"Successfully converted: {result}");
}
else
{
Console.WriteLine("Conversion failed. Invalid input.");
}
// TryParse with different types
string boolText = "true";
if (bool.TryParse(boolText, out bool boolResult))
{
Console.WriteLine($"Boolean value: {boolResult}");
}Nullable Types
By default, value types cannot be null. Nullable types allow value types to have a null value:
// Nullable value types
int? nullableInt = null;
bool? nullableBool = null;
DateTime? nullableDate = null;
// Checking for null values
if (nullableInt.HasValue)
{
Console.WriteLine($"Value: {nullableInt.Value}");
}
else
{
Console.WriteLine("Value is null");
}
// Null coalescing operator
int actualValue = nullableInt ?? 0; // Use 0 if null
Console.WriteLine($"Actual value: {actualValue}");Working with Strings
Strings have many useful methods and properties:
string text = " Hello, World! ";
// String properties and methods
Console.WriteLine($"Length: {text.Length}");
Console.WriteLine($"Trimmed: '{text.Trim()}'");
Console.WriteLine($"Upper case: {text.ToUpper()}");
Console.WriteLine($"Lower case: {text.ToLower()}");
Console.WriteLine($"Contains 'World': {text.Contains("World")}");
// String manipulation
string replaced = text.Replace("World", "C#");
string[] words = text.Trim().Split(' ');
Console.WriteLine($"Replaced: {replaced}");
Console.WriteLine($"First word: {words[0]}");Arrays and Collections Preview
While we'll cover these in detail later, here's a quick preview of storing multiple values:
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine($"First number: {numbers[0]}");
Console.WriteLine($"Array length: {numbers.Length}");
// Array of strings
string[] names = new string[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
Console.WriteLine($"Second name: {names[1]}");Practice Exercise
Try creating a simple program that demonstrates different data types:
using System;
// Create variables of different types
// Convert between types
// Display the results with proper formatting
// Handle user input safely
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
if (int.TryParse(ageInput, out int age))
{
// Calculate birth year
int currentYear = DateTime.Now.Year;
int birthYear = currentYear - age;
Console.WriteLine($"You were born in approximately {birthYear}");
Console.WriteLine($"In 10 years, you'll be {age + 10} years old");
}
else
{
Console.WriteLine("Please enter a valid number for your age.");
}Understanding variables and data types is fundamental to C# programming. These concepts form the building blocks for more complex programming constructs you'll learn next.
Last updated on