← C# EnglishChapter 02 of 13

Variables and Data Types

## Learning Objectives - Declare and initialize variables - Understand value types and reference types - Work with nullable types - Master type conversion ## Variables ### Declaration ```csharp int age; // Declaration age = 25; // Assignment int score = 100; // Declaration + Initialization ``` ### Naming Rules - Start with letter or underscore - Can contain numbers (after first character) - Cannot use reserved words - Case-sensitive - Cannot have whitespace ```csharp int age; // Valid int _count; // Valid int totalScore; // Valid int 2ndPlace; // Invalid - starts with number int class; // Invalid - reserved word ``` ## Value Types ### Integer Types | Type | Size | Range | |------|------|-------| | sbyte | 1 byte | -128 to 127 | | short | 2 bytes | -32,768 to 32,767 | | int | 4 bytes | -2.1B to 2.1B | | long | 8 bytes | Very large | | byte | 1 byte | 0 to 255 | | ushort | 2 bytes | 0 to 65,535 | | uint | 4 bytes | 0 to 4.2B | | ulong | 8 bytes | 0 to 18.4 quintillion | ```csharp byte b = 100; short s = 32000; int i = 2000000; long l = 9000000000L; // Note the L suffix ulong ul = 9000000000UL; // Unsigned long ``` ### Floating-Point Types | Type | Size | Precision | |------|------|-----------| | float | 4 bytes | ~6-7 digits | | double | 8 bytes | ~15-16 digits | | decimal | 16 bytes | 28-29 digits | ```csharp float pi = 3.14f; // Note the f suffix double precise = 3.14159265359; decimal money = 19.99m; // Note the m suffix (for currency) ``` ### Character Type ```csharp char grade = 'A'; char symbol = '\u0041'; // Unicode char newline = '\n'; ``` ### Boolean Type ```csharp bool isActive = true; bool hasPermission = false; ``` ## Reference Types ### Strings ```csharp string name = "Alice"; string greeting = new string("Hello"); string empty = string.Empty; string nullStr = null; ``` ### Arrays ```csharp int[] numbers = { 1, 2, 3, 4, 5 }; string[] names = new string[3]; ``` ### Classes ```csharp string name = "Alice"; // String is a class object obj = new object(); ``` ## Nullable Types ### Value Types Can Be Null ```csharp int? nullableInt = null; double? nullableDouble = 3.14; if (nullableInt.HasValue) { Console.WriteLine(nullableInt.Value); } // Or use null coalescing int value = nullableInt ?? 0; ``` ### Reference Types Are Nullable by Default ```csharp string name = null; // Valid for reference types ``` ## The var Keyword ### Implicit Typing ```csharp var name = "Alice"; // Compiler infers string var age = 25; // Compiler infers int var list = new List(); // Long type inferred // Cannot change type after inference var x = 10; // x = "hello"; // Error - x is int ``` ### When to Use var ```csharp // Good use - clear from right side var person = new Person("Alice", 25); var dictionary = new Dictionary(); var numbers = new[] { 1, 2, 3 }; // Bad use - unclear type var obj = GetSomeObject(); // What type is this? ``` ## Type Conversion ### Implicit (Widening) ```csharp int i = 100; long l = i; // int to long (automatic) double d = i; // int to double (automatic) ``` ### Explicit (Narrowing) ```csharp double d = 3.99; int i = (int)d; // Truncates to 3 // With overflow checking int big = 300; checked { byte b = (byte)big; // OverflowException } ``` ### String to Number ```csharp string s = "123"; int i = int.Parse(s); double d = double.Parse(s); // With error handling try { int result = int.Parse("abc"); } catch (FormatException) { Console.WriteLine("Invalid number"); } // TryParse - safer approach if (int.TryParse(s, out int result)) { Console.WriteLine("Parsed: " + result); } else { Console.WriteLine("Could not parse"); } ``` ### Number to String ```csharp int i = 42; string s = i.ToString(); string s2 = Convert.ToString(i); string s3 = "" + i; // Concatenation ``` ### Convert Class ```csharp int i = 42; double d = Convert.ToDouble(i); string s = Convert.ToString(i); bool b = Convert.ToBoolean(1); // true ``` ## Constants ### const vs readonly ```csharp const double PI = 3.14159; const int MAX_SIZE = 100; // const must be initialized at compile time // PI = 3.14; // Error! // readonly - can be set at runtime class Person { readonly int _createdAt; public Person() { _createdAt = DateTime.Now.Year; } } ``` ## Variables Scope ```csharp public class Scope { int global = 10; // Instance variable public void Method() { int local = 20; // Local variable for (int i = 0; i < 5; i++) // Block variable { // i only exists in this loop } } } ``` ## Value Type vs Reference Type ```csharp // Value type - copy of value int a = 10; int b = a; b = 20; // a is still 10 // Reference type - copy of reference int[] arr1 = { 1, 2, 3 }; int[] arr2 = arr1; arr2[0] = 99; // arr1[0] is also 99 (same array) ``` ## Default Values ```csharp int i = default; // 0 bool b = default; // false string s = default; // null int[] arr = default; // null // Explicit defaults int zero = default(int); bool flag = default(bool); ``` ## Summary - Variables store data values - Value types: int, long, float, double, decimal, bool, char - Reference types: string, arrays, objects - Use `const` for compile-time constants - Use `readonly` for runtime constants - `var` infers type from right side - Implicit conversion is automatic; explicit requires cast - `int.TryParse()` is safer than `int.Parse()`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →