C# Data Types and Principles
Data Representation
- Data is represented by constants and variables.
- Constants do not change.
- Variables can change.
C# Types
- C# has 15 basic types and 6 groups:
- Numeric (Integrals or floating point)
- String (Text)
- Characters (Individual characters)
- Boolean (True or False)
- Enums (Set of values)
- Classes (Data and behaviour)
Integral Types
- Represent whole numbers without decimal points.
- Store positive, negative, or zero.
- C# is a statically typed language.
- Different integral types have different ranges and memory sizes.
- Default value for a variable is 0.
- Default type of a literal is a signed integer (int).
- Min and max values can be retrieved using
TypeName.MinValue and TypeName.MaxValue.
Integral Types Table
byte: System.Byte, 1 byte, unsigned (0 to 255).sbyte: System.SByte, 1 byte, signed (-128 to 127).ushort: System.UInt16, 2 bytes, unsigned (0 to 65,535).short: System.Int16, 2 bytes, signed (-32,768 to 32,767).uint: System.UInt32, 4 bytes, unsigned (0 to 4,294,967,295).int: System.Int32, 4 bytes, signed (-2,147,483,648 to 2,147,483,647).ulong: System.UInt64, 8 bytes, unsigned (0 to ~1.8∗1019).long: System.Int64, 8 bytes, signed (~−9.2∗1018 to ~9.2∗1018).
Integral Operators
- Operators are actions, operands are data.
- Examples:
- "25+25=50"
- "100−10=90"
- "10∗10=100"
- "200/10=20"
- "75/100=0" (integer division)
- "16 (remainder)
C# as a Statically Typed Language
- Variable's type must be declared.
- Variables must be declared before use.
- Variables can only be declared once.
- Variable's type cannot be changed.
- Type error checking is performed at compile time.
- Memory is reserved at compile time.
Variable Declaration, Initialisation & Assignment
- Declaration:
TYPE IDENTIFIER; - Initialisation:
TYPE IDENTIFIER = VALUE; - Assignment:
IDENTIFIER = VALUE;
Shortcut Arithmetic Operators
x += y; is equivalent to x = x + y;x -= y; is equivalent to x = x - y;x *= y; is equivalent to x = x * y;x /= y; is equivalent to x = x / y;x++; is equivalent to x = x + 1; (increment)x--; is equivalent to x = x - 1; (decrement)
Variable Identifiers
- Meaningful and descriptive.
- Rules:
- Start with a letter, underscore ('_'), or at character ('@').
- Can contain letters, digits, and underscores after the first character.
- No spaces (use title case, camel case, or underscores).
- Case-sensitive.
- Cannot be reserved words without an ('@') prefix.
Only Declared Once
- Variables can only be declared once.
One Type
- Variables can only be declared as one type.
Constants
- Similar to variables but can only be initialised.
- Cannot be declared without assignment or reassigned.
- Initialisation:
const TYPE IDENTIFIER = VALUE;
Errors
- Compile time errors: Detected during compilation.
- Runtime errors: Occur while the program is running.
Statically vs Dynamically Typed
| Feature | Statically Typed | Dynamically Typed |
|---|
| Type Declaration | Types must be declared | Types are not declared |
| Type Change | Types cannot be changed | Types can be changed |
| Type Checking | Compile time | Run time |
| Memory Reservation | Compile time | Run time |
Floating Point Numbers
- Types:
float, double, decimal
Floating Point Numeric Types Table
float: System.Single, 4 bytes, ~6-9 digits precision.double: System.Double, 8 bytes, ~15-17 digits precision.decimal: System.Decimal, 16 bytes, ~28-29 digits precision.- Default value is 0.
double is the default type for a literal (e.g., 3.14).- Suffix
f or F to specify a float literal (e.g., 3.14f). - Use
x.0 to explicitly define an integral number as a floating point (e.g., 42.0). - Use
System.Double.NaN for 'Not a Number'.
Floating Point Operators
- Similar to integral types, but division is more accurate.
Characters
- Represented by the type
char. - Can be Unicode or special characters.
Character Type
char: System.Char, 2 bytes, Unicode character.- Default value:
0x0000 (0).
Escape Sequences
'\'': Single quote'\"': Double quote'\t': Tab'\n': New line (Unix systems)'\r': Carriage return (Non-Unix systems)'\\ ': Backslash
Strings
- Text values delimited by double quotes.
- Stored as a series of Unicode characters + additional info.
- Variable size (proportional to length).
IDENTIFIER.Length returns the number of characters.- Max length ~2 billion characters.
- Each string is a reference to the data.
- Immutable: every change creates a new reference and string.
- Default value is
null.
String Type
string: System.String, Unicode string, up to 2 billion characters.
String Indexing
- Strings can be indexed to access individual characters.
- Index starts at 0.
String Operators
+: String concatenation.+=: String combine (concatenates and overwrites).
String Methods
Trim(): Removes spaces at the beginning and end of the string.ToUpper(): Converts all letters to uppercase.ToLower(): Converts all letters to lowercase.IndexOf(char c): Returns the first index of c.LastIndexOf(char c): Returns the last index of c.Replace(string s1, string s2): Replaces occurrences of s1 with s2.
Console.WriteLine(): Writes a string followed by a newline.Console.Write(): Writes a string without a newline.Console.ReadLine(): Reads a string entered by the user.
Floating Point Output
- Uses scientific representation when very large or small.
Type Conversions
Implicit Conversions
- Lower amount of memory -> higher amount of memory
- Signed integrals -> Higher signed integrals
- Unsigned integrals -> Higher unsigned or signed integrals
Rules:
- Lower to Higher
- Signed integrals -> Higher signed integrals
- Unsigned integrals -> Higher unsigned or signed integrals
- Cannot convert between signed and unsigned within the type pair
- All Integrals -> Floating point; No floating point -> Integrals
- No float, double -> decimal
- Nothing can be converted to byte, sbyte
- Double and decimal cannot be converted to anything
Explicit Conversions
- Use casting:
(TYPE) EXPRESSION - Float to int could decrease the precision
Converting Non-strings to Strings
ToString()- String concatenation
- Composite format strings
- String interpolation
Verbatim Strings
- Use
@ to create strings that extend across multiple lines and contain embedded double quotes and backslashes. - Example:
string longString = @"This string extends across multiple lines..."
| Character | Name | Description |
|---|
E or e | Scientific | Scientific notation. |
G or g | General | Most compact form. |
F or f | Fixed | Fixed number of digits after the decimal point. |
N or n | Number | Fixed formatting with commas to separate thousands. |
C or c | Currency | Number formatting with a dollar sign. |
P or p | Percent | Multiplies the number by 100 and adds a percent sign. |
D or d | Decimal | Add leading zeros to the number General number |
- Additional formatting and alignment using composite formatting or string interpolation.
Converting String to Non-Strings
- Use
Convert.To or Parse methods.
Testing
- Valid data: Data the program is expected to use.
- Invalid data: Data the program is not expected to use.
Common Tests
- Numeric ranges include zero, positive, negative numbers, upper/lower limits.
- String lengths include empty strings, single characters, various sizes.