Environment
- instantiate a new csharp project: enter the folder and
dotnet new console --framework net7.0 to create a new console project
- access through vscode: build, run, etc.
- access through terminal:
dotnet build and dotnet run
Debug with vscode: the configuration file. See
here
for what each of these does, but I guess they don't matter that much in our case.
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net7.0/test.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
Basis
Data Types
value types (primitives: integral, floating-point...) and reference types (objects: string, array...).
value types are disposed after stack is destroyed because they are stored on the stack, but reference types
remain in memory.
- value types
- integral types:
sbyte, short, int, long and byte, ushort, uint, ulong
- floating-point types:
float, double, decimal
char
bool
enum E {...} user defined, a set of named constant
- nullable values:
int? nullableInt;
- tuple value
(double, int) tuple1 = (4.5, 3);
- reference types
- class:
string is also a class type
- interface: same as Java, cannot have detailed method implementation
- array
- delegate
char c = 'c';
int i = 123;
decimal d = 1.23m;
// float: 32 bit, double: 64 bit, decimal: 128 bit
// by default it's double, use suffix f for float and m for decimal
string s = "hello";
bool b = true;
can also declare variables implicitly with
var, but data type is fixed once you declare it.
Three way type conversions between numeric data:
- casting with curly brackets, e.g.,
int num = (int)(1.5m); // num=1
- casting with suffices, e.g.,
decimal num = 1.5m
- this is NOT casting,
Convert.ToInt32(1.5m)=2. it rounds up instead of truncate
// this line prints Windows 74 instead of Windows 11
Console.WriteLine("Windows " + 7 + 4);
Naming Conventions
- should NOT use abbreviations, e.g.,
tmp is a bad idea
- should NOT contain the data type, e.g.,
myStr is a bad idea
- methods should be capitalized, e.g.
PrintMyName()
Methods
stateful (instance) vs stateless methods (static):
the former relies on memory, the latter does not, i.e., need to instantiate for stateful method but not need for
stateless ones.
csharp is pass by value. If you want to pass by reference, you can use the
ref keyword.
named arguments and optional arguments
// original func declaration
void RSVP(string name, int partySize, string allergies, bool inviteOnly);
//named arguments: make func calls without specifying order by specifying the names of the params
RSVP(name: "Linh", partySize: 2, allergies: "none", inviteOnly: false);
// optional arguments: set default values for the func declaration
void RSVP(string name, int partySize = 1, string allergies = "none", bool inviteOnly = true);
Exception Handling
try{
// can also use the checked keyword for OverflowException, which truncates the most significant bits
} catch (Exception ex) {
// ex.Message, ex.StackTrace...
} finally {
// clean up
}
types of exceptions:
- compiler generated: you can't instantiate with
new, you can only catch them
ArrayTypeMismatchException array can't store a particular data type because of type
mismatch
DivideByZeroException
FormatException invalid argument formatting, e.g. Parse()
IndexOutOfRangeException
InvalidCastException
NullReferenceException
OverflowException arithmatic operation overflows
- customized: create a new instance with
new, then throw it
can pass Message to the constructor, but once you set it, it's readonly.
ArgumentException invalid arguments
InvalidOperationException depending on the state of the object, a certain operation
may be invalid
NotSupportedExceptionregardless of the state of the object, the operation is always
invalid
IOException
FormatException string or output formatting
Others
using System needed for IO. etc, pretty much the same thing as using namespace std. usually
included by default.
switch in c#: possible to put multiple tags together like so
case 1: case 2: return true;
Data Structures
Array
// declare and initialize: 2 ways
string[] names = new string[3]; // then initialize
string[] names = { "Amy", "Bob", "Carly" };
// iterate through an array: 2 ways
// note that you CAN'T modify values in the array with foreach
foreach (string name in names){...}
for (int i=0; i<names.Length; i++){...}
Array functions:
Array.Sort(names);
Array.Reverse(names);
Array.Clear(names, idx, num); // set [num] elements starting at [idx] to null, but the length of the array is unchanged.
Array.Resize(ref names, size); // resize the array to [size], padded with null element or remove the last few elements
// there is no method to remove null elements only
WPF
WPF is Windows Presentation Foundation, basically a framework used to build windows desktop app; it is primarily
in c sharp (frontend UI).
XAML
- a variant of xml, looks like React. case sensitive.
- converts tabs into spaces; preserves only one space if there are many
- attributes need to be set as strings, e.g.,
<Thickness Left="10">
<!-- root element -->
<Page x:Class="index.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
</Page>
<StackPanel> <!-- object syntax -->
<Button Click="Button_Clicked"/> <!-- attribute syntax -->
</StackPanel>
<Button> <!-- property element syntax -->
<Button.Content>
This is a button
</Button.Content>
</Button>
Modal-View-ViewModel Design Pattern