Skip to content

Instantly share code, notes, and snippets.

@ZapDos7
Last active September 19, 2023 17:43
Show Gist options
  • Save ZapDos7/ab6c4acda00aba0fc6525de59a70e1a3 to your computer and use it in GitHub Desktop.
Save ZapDos7/ab6c4acda00aba0fc6525de59a70e1a3 to your computer and use it in GitHub Desktop.
  • Print: Console.WriteLine("Hello World!"); (with new line) or Console.Write("Hello World!"); (no new line)
  • Literals:
    • 0.25F - fp
    • 0.25 - double
    • 12.39816m - decimal
  • Declare: string s = "a";
  • Implicit declaration: var text = "some string"; - must be initialized!
  • Verbatim string literal:
Console.WriteLine(@"    c:\source\repos    
        (this is where your code goes)");

prints

c:\source\repos    
        (this is where your code goes)
  • Unicode escape chars
// Kon'nichiwa World
Console.WriteLine("\u3053\u3093\u306B\u3061\u306F World!");

prints

こんにちは World!
  • String interpolation:
string message = $"{greeting} {firstName}!";
// same as
string message = greeting + " " + firstName + "!";
  • Verbatim x String Interpolation
string projectName = "First-Project";
Console.WriteLine($@"C:\Output\{projectName}\Data");

prints

C:\Output\First-Project\Data
  • Force addition when string manipulating:
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + (widgetsSold + 7) + " widgets.");

prints

Bob sold 14 widgets.

and not

Bob sold 77 widgets.
  • wrong calculations:
int decimalQuotient = 7 / 5.0m;
int decimalQuotient = 7.0m / 5;
int decimalQuotient = 7.0m / 5.0m;
decimal decimalQuotient = 7 / 5;

returns

(1,5): error CS0219: The variable 'decimalQuotient' is assigned but its value is never used
(1,23): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)
(2,5): error CS0128: A local variable or function named 'decimalQuotient' is already defined in this scope
(2,5): error CS0219: The variable 'decimalQuotient' is assigned but its value is never used
(2,23): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)
(3,5): error CS0128: A local variable or function named 'decimalQuotient' is already defined in this scope
(3,5): error CS0219: The variable 'decimalQuotient' is assigned but its value is never used
(3,23): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)
(4,9): error CS0128: A local variable or function named 'decimalQuotient' is already defined in this scope
(4,9): error CS0219: The variable 'decimalQuotient' is assigned but its value is never used
  • for loops:
string[] names = { "Rowena", "Robin", "Bao" };
foreach (string name in names)
{
   Console.WriteLine(name);
}
  • arrays: string[] fraudulentOrderIDs = new string[3];
  • array length: Console.WriteLine($"There are {fraudulentOrderIDs.Length} fraudulent orders to process.");
  • execute with dotnet run
  • read user input: Console.ReadLine()
  • inline conditional operator:
int saleAmount = 1001;
// int discount = saleAmount > 1000 ? 100 : 50;
Console.WriteLine($"Discount: {(saleAmount > 1000 ? 100 : 50)}");
  • switch-case
switch (fruit)
{
    case "apple":
        Console.WriteLine($"App will display information for apple.");
        break;

    case "banana":
        Console.WriteLine($"App will display information for banana.");
        break;

    case "cherry":
        Console.WriteLine($"App will display information for cherry.");
        break;
}
  • TryParse(): The TryParse() method does several things simultaneously:
    • It attempts to parse a string into the given numeric data type.
    • If successful, it stores the converted value in an out parameter, explained in following section.
    • It returns a bool to indicate whether the action succeeded or failed.
  • Array methods:
    • .clear(arrayName, startingIndex, amountOfElementsToBeCleared) - empties a array
    • sort() - sorts elements of array
    • resize(ref arrayName, newNumOfElements) - resizes an array
    • Reverse(valueArray) - reverses elements in array
  • String methods:
    • string result = String.Join(",", valueArray); : appends array elements separated by a comma to a string
    • string[] items = result.Split(','); - performs the opposite task
  • string first = "Hello";
    string second = "World";
    Console.WriteLine("{1} {0}!", first, second);
    Console.WriteLine("{0} {0} {0}!", first, second);

prints

World Hello!
Hello Hello Hello!
  • Format currency:
decimal price = 123.45m;
int discount = 50;
Console.WriteLine($"Price: {price:C} (Save {discount:C})");

prints

Price: $123.45 (Save $50.00)

culture codes specify the currency symbol (e.g. en-US for $, fr-FR for etc

  • We can format percentages similarly:
Console.WriteLine($"Tax rate: {tax:P2}");
// prints: Tax rate: 36.79 %

and large numbers:

Console.WriteLine($"Measurement: {measurement:N4} units");
// prints Measurement: 123,456.7891 units
  • String padding:
string myWords = "Learning C#"`;
Console.WriteLine(myWords.PadLeft(12));
// one space is added, since myWords is 11 characters long, so adding on space completes the padding to 12.
  • This method returns a 2D array of strings & has optional parameter groups.
string[,] AssignGroup(int groups = 6) { /*implementation*/}
  • exception handling:
try
{
    // Step 1: code execution begins
    try
    {
        // Step 2: an exception occurs here
    }
    finally
    {
        // Step 4: the system executes the finally code block associated with the try statement where the exception occurred
        // used to clean up resources allocated in "try" block
    }

}
catch // Step 3: the system finds a catch clause that can handle the exception
{   
   // Step 5: the system transfers control to the first line of the catch code block
}
  • using - it affects all the code in the code file.
  • exceptions:
static void WriteMessage()
{
    double float1 = 3000.0;
    double float2 = 0.0;
    int number1 = 3000;
    int number2 = 0;
    byte smallNumber;

    try
    {
        Console.WriteLine(float1 / float2);
        Console.WriteLine(number1 / number2);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine($"Exception caught in WriteMessage: {ex.Message}");
    }
    checked
    {
        smallNumber = (byte)number1;
    }
}
  • checked: When performing integral type calculations that assign the value of one integral type to another integral type, the result depends on the overflow-checking context. In a checked context, the conversion succeeds if the source value is within the range of the destination type. Otherwise, an OverflowException is thrown. In an unchecked context, the conversion always succeeds, and proceeds as follows:

If the source type is larger than the destination type, then the source value is truncated by discarding its "extra" most significant bits. The result is then treated as a value of the destination type.

If the source type is smaller than the destination type, then the source value is either sign-extended or zero-extended so that it's of the same size as the destination type. Sign-extension is used if the source type is signed; zero-extension is used if the source type is unsigned. The result is then treated as a value of the destination type.

If the source type is the same size as the destination type, then the source value is treated as a value of the destination type.

Stateful versus stateless methods

In software development projects, the term state is used to describe the condition of the execution environment at a specific moment in time. As your code executes line by line, values are stored in variables. At any moment during execution, the current state of the application is the collection of all values stored in memory.

Some methods don't rely on the current state of the application to work properly. In other words, stateless methods are implemented so that they can work without referencing or changing any values already stored in memory. Stateless methods are also known as static methods.

For example, the Console.WriteLine() method doesn't rely on any values stored in memory. It performs its function and finishes without impacting the state of the application in any way.

Other methods, however, must have access to the state of the application to work properly. In other words, stateful methods are built in such a way that they rely on values stored in memory by previous lines of code that have already been executed. Or they modify the state of the application by updating values or storing new values in memory. They're also known as instance methods.

Stateful (instance) methods keep track of their state in fields, which are variables defined on the class. Each new instance of the class gets its own copy of those fields in which to store state.

A single class can support both stateful and stateless methods. However, when you need to call stateful methods, you must first create an instance of the class so that the method can access state.

  • Regex: C# regex implicit word boundaries: The \w is a character class used for a character allowed in a word. For the \w+ regular expression, which denotes a word, the leading and trailing word boundary metacharacters are implicit; i.e. \w+ is equal to \b\w+\b.
  • Public class with public getter, private setter: public int confirmed { get; private set; }
  • Equality check details: The == operator performs a default equality comparison between the values, while the Equals() method can be overridden to provide customized comparison logic if needed
  • Delegates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment