Learning CSharp basics part-1 data types
I’m diving into C# and finding the Microsoft training resources helpful. For folks coming from dynamic languages like Python or JavaScript, it is important to understand C#‘s data types first. I’m currently following the Get Started with C# Guided Paths and part 1 covers data types. I went through first part but needed more sources to better understand data types and I taught it would help other beginners too.
Data Types in C#: “value types” and “reference types”
Data Types define the kind of values a variable can hold to ensure type safety and efficient memory management.Types are either “value types” or “reference types”. Reference types, store references to the actual data stored in memory, but value types, store their data directly in memory.
Value Types
-
Integral numeric types:
- int for whole numbers -2,147,483,648 to 2,147,483,647
- long for larger whole numbers -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
- short for smaller integers from -32,768 to 32,767
- byte for unsigned integers from 0 to 255
-
Floating-point numeric types:
- double for decimal values requiring high precision. ex. double pi = 3.141592653589793238462643
- float for decimal values where memory efficiency is important. ex. float celcius = 22.3f. “f” suffix stands for float.
-
Boolean types: for logical values “true” and “false”
-
Character type: for single character. ex. char up = ‘w’; char down = ‘a’
-
Nullable value types: for value types that can also be null.
In the beginning of learning csharp, you may see the warning for possible null value like the image below.
💡
String type in C# is a reference type and by default it is nullable, but VSCode intellisense throws a warning. To read more about nullable value types visit Microsoft's reference page for nullable.
VSCode Intellisense suggests converting string to nullable data type by suffixing "?" to data type but it is better idea to assign a default value to variable and make it non-nullable instead.
// Converting data type to nullable
string name1 = Console.ReadLine();
string? name2 = Console.ReadLine();
// make variable "name" non-nullable by assigning default value to variable
string name3 = Console.ReadLine() ?? "John Doe";
Console.WriteLine($"Hello {name3}");
Refernce Types
- Class type: for when you create an instance of a class (object) using the new keyword. Example: Random dice = new Random();
- String type: for sequences of characters. Example: string name = “John Doe”;
- Array type: for collections of values of the same data type. Example: int[] numbers = {1, 2, 3, 4};
- Interface type: Defines contracts that classes must follow.
Formatting literal strings in C#
-
Use character escape sequences when you need to insert a special character into a literal string, like a tab \t, new line \n, or a nested quotation mark \“.
-
Use an escape character for the backslash \ when you need to use a backslash in all other scenarios.
-
Use the @ directive to create a verbatim string literal that keeps all whitespace formatting and backslash characters in a string.
-
Use the \u plus a four-character code to represent Unicode characters (UTF-16) in a string. Unicode characters may not print correctly depending on the application.
single quotation mark for char type and double quotation mark for strings.
char one_letter = 'a';
string msg = "first quotation mark and \"this is the second quotaion mark\""; // output: first quotation mark and "this is the second quotaion mark"
String Concatenation
string msg = greeting + " " + firstName + "!";
String Interpolation
string msg = $"{greeting} {firstName}!";
Combine verbatim literals and string interpolation
To output the string as
string projectName = "First-Project"; Console.WriteLine($@"C:\Output\{projectName}\Data"); // output: C:\Output\ACME\Data
Math operation
- Both string concatenation and addition use the plus + symbol. This is called overloading an operator, and the compiler infers the proper use based on the data types it’s operating on.
- When it can, the C# compiler will implicitly convert an int into a string if it’s obvious that the developer is trying to concatenate the string representation of a number for presentation purposes.
- Use parentheses to define an order of operations to explicitly tell the compiler that you want to perform certain operations before other operations.
To define a decimal literal from an integer in C#, you can add "m" to the integer. The "m" itself doesn't have a specific meaning but serves as a suffix to distinguish the number as a decimal literal. This choice was made because "d" is already used for double-precision floating-point numbers. Using "m" helps ensure the compiler treats the number as a decimal.
// at least, one of the operands need to be defined as decimal
decimal val1 = 1/2m; // output: 0.5
decimal val2 = 1/2; // output: 0
decimal val3 = 3/2; // output: 1
// assigning variable type as "decimal" won't affect the result
int val4 = 5/2; // output: 2
decimal val5 = 5/2; // output: 2
decimal val6 = 5/2m; // output: 2.5
More examples:
// module
int three = 8 % 5; // output: 3
string firstName = "Bob";
int bagsSold = 7;
Console.WriteLine(firstName + " sold " + bagsSold + 7 + " bags."); // Output: Bob sold 77 bags
Console.WriteLine(firstName + " sold " + (bagsSold + 7) + " bags."); // Output: Bob sold 14 bags
int value = 1;
value = value + 1;
Console.WriteLine("First increment: " + value); // output: 2
value += 1; // output: 3
value++; // output: 4
value = value - 1;
Console.WriteLine("First decrement: " + value); // output: 3
value -= 1; // output: 2
value--; // output: 1
In math, PEMDAS is an acronym that helps students remember the order of operations. The order is:
- Parentheses (whatever is inside the parenthesis is performed first)
- Exponent
- Multiplication and Division (from left to right)
- Addition and Subtraction (from left to right)
Console.WriteLine("Windows " + 7 + 4); // output: Windows 74
int res = 3 + 1 * 5 / 2;
Console.WriteLIne(res); // output: 5
Console.WriteLine(5 / 10); // output: 0
Console.WriteLine(5m / 10); // output: 0.5
3 use case for the parenthesis operator
- method invocation
- order of operations (ex: int val1 = (3 + 4) * 5;)
- casting (ex: data type cast from int to decimal)
// convert fahrenheit to celcius
int fahrenheit = 94;
double celcius = (fahrenheit - 32) * 5m / 9;
celcius = Math.Round(celcius, 2);
Console.WriteLine($"The temrature is {celcius} celcius."); // output: The temrature is 34.44
Formatting console output with tab and newline
To print out tab spaces, use \t and for new line use \n .
// initialize variables - graded assignments
int currentAssignments = 4;
int sophia1 = 93;
int sophia2 = 87;
int sophia3 = 98;
int sophia4 = 95;
int nicolas1 = 80;
int nicolas2 = 83;
int nicolas3 = 82;
int nicolas4 = 88;
// sum variables
int sophiaSum = sophia1 + sophia2 + sophia3 + sophia4 ;
int nicolasSum = nicolas1 + nicolas2 + nicolas3 + nicolas4;
// calculating average
decimal sophiaScore = (decimal) sophiaSum / currentAssignments;
decimal nicolasScore = (decimal) nicolasSum / currentAssignments;
// or:
// decimal sophiaScore = sophiaSum / 4m;
Console.WriteLine("Student\t\tGrade\n");
Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA");
Console.WriteLine("Nicolas:\t\t" + nicolasScore + "\tB");
// output:
// Student Grade
// Sophia: 94.6 A
// Nicolas: 83.6 B