Csharp basics study notes - W3schools
Reference
C# Tutorial (C Sharp) (w3schools.com)
Get started
C# is an object-oriented programming language created by Microsoft that runs on the .NET Framework.
The first version was released in year 2002. The latest version, C# 12, was released in November 2023.
两种运行cs程序的方式:
VS 中
How to run C# project: How to run a program (C#) - Visual Studio (Windows) | Microsoft Learn
csproj 目录下运行
dotnet runHow to run C# project in VS Code: [How to Run C# in VSCode (and Compile, Debug, and Create a Project) (travis.media)](https://travis.media/how-to-run-csharp-in-vscode/#:~:text=How to Run C%23 in VSCode 1 1.,Your Code To compile your code%2C run%3A )
1
2
3
4
5
6
7
8# create a C# project
dotnet new console -o app
cd app
code . # to open project in VSCode
# run
dotnote run
# generate executable file
dotnet buid
C# Syntax
1 | using System; |
using Systemmeans that we can use classes from theSystemnamespace.namespaceis used to organize your code, and it is a container for classes and other namespaces.classis a container for data and methods, which brings functionality to your program. Every line of code that runs in C# must be inside a class. In our example, we named the class Program.Consoleis a class of theSystemnamespace, which has aWriteLine()method that is used to output/print text. In our example, it will output “Hello World!”.If you omit the
using Systemline, you would have to writeSystem.Console.WriteLine()to print/output text.Unlike Java, the name of the C# file does not have to match the class name, but they often do (for better organization).
1 | // ========== Output ========== |
| Data Type | Size | Description |
|---|---|---|
int |
4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long |
8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float |
4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double |
8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
bool |
1 bit | Stores true or false values |
char |
2 bytes | Stores a single character/letter, surrounded by single quotes |
string |
2 bytes per character | Stores a sequence of characters, surrounded by double quotes |
1 | // ========== Type Casting ========== |
| Operator | Name | Description | Example |
|---|---|---|---|
| + | Addition | Adds together two values | x + y |
| - | Subtraction | Subtracts one value from another | x - y |
| * | Multiplication | Multiplies two values | x * y |
| / | Division | Divides one value by another | x / y |
| % | Modulus | Returns the division remainder | x % y |
| ++ | Increment | Increases the value of a variable by 1 | x++ |
| – | Decrement | Decreases the value of a variable by 1 | x– |
| Operator | Example | Same As |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
| &= | x &= 3 | x = x & 3 |
| |= | x |= 3 | x = x | 3 |
| ^= | x ^= 3 | x = x ^ 3 |
| >>= | x >>= 3 (移位,/2) | x = x >> 3 |
| <<= | *x <<= 3 (移位,2) | x = x << 3 |
| Operator | Name | Example |
|---|---|---|
| == | Equal to | x == y |
| != | Not equal | x != y |
| > | Greater than | x > y |
| < | Less than | x < y |
| >= | Greater than or equal to | x >= y |
| <= | Less than or equal to | x <= y |
| Operator | Name | Description | Example |
|---|---|---|---|
| && | Logical and | Returns True if both statements are true | x < 5 && x < 10 |
| || | Logical or | Returns True if one of the statements is true | x < 5 || x < 4 |
| ! | Logical not | Reverse the result, returns False if the result is true | !(x < 5 && x < 10) |
1 | // ========== Math ========== |
| Escape character | Result | Description |
|---|---|---|
| ' | ‘ | Single quote |
| " | “ | Double quote |
| \ | \ | Backslash |
| Code | Result |
|---|---|
| \n | New Line |
| \t | Tab |
| \b | Backspace |
1 | // ========== IF...Else ========== |
C# Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
In C#, it is good practice to start with an uppercase letter when naming methods, as it makes the code easier to read.
1 | // It is also possible to send arguments with the key: value syntax. |
Method Overloading 重载
With method overloading, multiple methods can have the same name with different parameters:
1 | public class Calculator |
Multiple methods can have the same name as long as the number and/or type of parameters are different.
Method Overriding 重写
notes is from Overloading Vs. Overriding in C# | HackerNoon
Overriding, on the other hand, is the ability to redefine the implementation of a method in a class that inherits from a parent class. When a method is overridden, the name and the parameters stay the same, but the implementation that gets called depends on the type of the object that’s calling it.
Overriding is known as runtime (or dynamic) polymorphism because the type of the calling object is not known until runtime, and therefore the method implementation that runs is determined at runtime.
As an example, imagine we have a base class called Dog with a Woof method. We mark the method as virtual to signify that this method can be overriden by inheriting classes.
1 | public class Dog |
Currently this and any inherited classes will use the Woof method defined in the Dog class:
1 | public class BigDog : Dog |
However, we can choose to override the method so that our inherited classes have a different implementation of Woof:
1 | public class YappyDog : Dog |
Here the base Dog class still uses it’s own implementation, but the inherited YappyDog has it’s own overridden implementation that it uses. The application checks at runtime what the type of the class is (Dog or YappyDog) and calls the method for that particular type.
C# Classes
A class is a template for objects, and an object is an instance of a class.
When a variable is declared directly in a class, it is often referred to as a field (or attribute).
It is not required, but it is a good practice to start with an uppercase first letter when naming classes. Also, it is common that the name of the C# file and the class matches, as it makes our code organized.
Using Multiple Classes
prog2.cs
1 | class Car |
prog.cs
1 | class Program |
Class members
Fields and methods inside classes are often referred to as “Class Members”.
1 | class Car |
A static method can be accessed without creating an object of the class, while public methods can only be accessed by objects.
Constructors 构造函数
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for fields.
1 | // Create a Car class |
All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you. However, then you are not able to set initial values for fields.
Just like other methods, constructors can be overloaded by using different numbers of parameters.
Access Modifiers
| Modifier | Description |
|---|---|
public |
The code is accessible for all classes |
private |
The code is only accessible within the same class |
protected |
The code is accessible within the same class, or in a class that is inherited from that class. |
internal |
The code is only accessible within its own assembly, but not from another assembly. |
There’s also two combinations: protected internal and private protected.
By default, all members of a class are private if you don’t specify an access modifier
Why Access Modifiers?
To control the visibility of class members (the security level of each individual class and class member).
To achieve “Encapsulation“ - which is the process of making sure that “sensitive” data is hidden from users. This is done by declaring fields as private.
Properties (Get and Set)
The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:
- declare fields/variables as
private - provide
publicgetandsetmethods, through properties, to access and update the value of aprivatefield
You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties.
A property is like a combination of a variable and a method, and it has two methods: a get and a set method:
1 | class Person |
Automatic Properties (Short Hand):
C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property.
1 | class Person |
Why Encapsulation?
- Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
- Fields can be made read-only (if you only use the
getmethod), or write-only (if you only use thesetmethod) - Flexible: the programmer can change one part of the code without affecting other parts
- Increased security of data
Inheritance
In C#, it is possible to inherit fields and methods from one class to another. We group the “inheritance concept” into two categories:
- Derived Class (child) - the class that inherits from another class
- Base Class (parent) - the class being inherited from
1 | class Vehicle // base class (parent) |
If you don’t want other classes to inherit from a class, use the sealed keyword:
If you try to access a sealed class, C# will generate an error:
1 | sealed class Vehicle |
The error message will be something like this:
1 | 'Car': cannot derive from sealed type 'Vehicle' |
Polymorphism 多态 (override)
Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.)
C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods.
1 | class Animal // Base class (parent) |
Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is used for classes and methods:
- Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
- Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).
1 | // Abstract class |
Interface
An interface is a completely “abstract class“, which can only contain abstract methods and properties (with empty bodies).
It is considered good practice to start with the letter “I” at the beginning of an interface, as it makes it easier for yourself and others to remember that it is an interface and not a class.
By default, members of an interface are abstract and public.
Note: Interfaces can contain properties and methods, but not fields.
To access the interface methods, the interface must be “implemented” (kinda like inherited) by another class.
Note that you do not have to use the override keyword when implementing an interface.
1 | // Interface |
Notes on Interfaces:
- Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an “IAnimal” object in the Program class)
- Interface methods do not have a body - the body is provided by the “implement” class
- On implementation of an interface, you must override all of its methods
- Interfaces can contain properties and methods, but not fields/variables
- Interface members are by default
abstractandpublic - An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
To achieve security - hide certain details and only show the important details of an object (interface).
C# does not support “multiple inheritance” (a class can only inherit from one base class). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
1 | interface IFirstInterface |
Enum (enumerations) 枚举类型
An enum is a special “class” that represents a group of constants (unchangeable/read-only variables).
1 | class Program |
By default, the first item of an enum has the value 0. The second has the value 1, and so on.
1 | enum Months |
You can also assign your own enum values, and the next items will update their numbers accordingly:
1 | enum Months |
Enum in a Switch Statement:
1 | enum Level |
Why And When To Use Enums?
Use enums when you have values that you know aren’t going to change, like month days, days, colors, deck of cards, etc.
Files
The File class from the System.IO namespace, allows us to work with files.
The File class has many useful methods for creating and getting information about files. For example:
| Method | Description |
|---|---|
AppendText() |
Appends text at the end of an existing file |
Copy() |
Copies a file |
Create() |
Creates or overwrites a file |
Delete() |
Deletes a file |
Exists() |
Tests whether the file exists |
ReadAllText() |
Reads the contents of a file |
Replace() |
Replaces the contents of a file with the contents of another file |
WriteAllText() |
Creates a new file and writes the contents to it. If the file already exists, it will be overwritten. |
Exceptions - Try..Catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
1 | try |
The output will be:
1 | Index was outside the bounds of the array. |
The finally statement lets you execute code, after try...catch, regardless of the result:
1 | try |
The output will be:
1 | Something went wrong.The 'try catch' is finished. |
The throw statement allows you to create a custom error.
The throw statement is used together with an exception class. There are many exception classes available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc:
1 | static void checkAge(int age) |