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

  1. Integral numeric types:

    1. int for whole numbers -2,147,483,648 to 2,147,483,647
    2. long for larger whole numbers -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
    3. short for smaller integers from -32,768 to 32,767
    4. byte for unsigned integers from 0 to 255
  2. Floating-point numeric types:

    1. double for decimal values requiring high precision. ex. double pi = 3.141592653589793238462643
    2. float for decimal values where memory efficiency is important. ex. float celcius = 22.3f. “f” suffix stands for float.
  3. Boolean types: for logical values “true” and “false”

  4. Character type: for single character. ex. char up = ‘w’; char down = ‘a’

  5. 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.

possible null value warning in csharp


💡
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


  1. Class type: for when you create an instance of a class (object) using the new keyword. Example: Random dice = new Random();
  2. String type: for sequences of characters. Example: string name = “John Doe”;
  3. Array type: for collections of values of the same data type. Example: int[] numbers = {1, 2, 3, 4};
  4. Interface type: Defines contracts that classes must follow.

Formatting literal strings in C#

  1. ​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 \“.

  2. Use an escape character for the backslash \ when you need to use a backslash in all other scenarios.

  3. Use the @ directive to create a verbatim string literal that keeps all whitespace formatting and backslash characters in a string.

  4. 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

  1. 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.
  2. 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.
  3. 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:

  1. Parentheses (whatever is inside the parenthesis is performed first)
  2. Exponent
  3. Multiplication and Division (from left to right)
  4. 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

  1. method invocation
  2. order of operations (ex: int val1 = (3 + 4) * 5;)
  3. 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



Tags: