C# Quick Start

Kesa2023年4月2日...大约 7 分钟NoteC#Tutorial

C# is a programming language developed by Microsoft that runs on the .NET framework.

1. Syntax

1.1 Hello World

using System;

namespace HelloWorld
{
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

1.2 Comments

Single-line Comments

Start with two forward slashes //.

// this is a comment
Console.WriteLine("Hello"); // Comment here

Multi-line Comments

Start with /* and ends with */, any text between these will be ignored by C#.

/* This is the 
 * multi-line Comment
 */
Console.WriteLine("Hello World");

1.4 Variables

Declare Variables

// Single varible
// type variableName = value;
int myAge = 10;
string name;
// Mutilple variables
/// type n1 = v1, n2 = v2 ...
int x = 1, y =2;
int u, v;

Constants

Add const keyword in front of the variable type will declare it as “constant” which means unchanged and read-only.

const in myAge = 10;
// error
// myAge = 11;

Identifier

All C# variables must be identified with unique names that called identifiers.

Rules of naming variables :

2. Data Type

Data TypeSizeDescription
int4 bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
long8 bytesStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4 bytesStores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
bool1 bitStores true or false values
char2 bytesStores a single character/letter, surrounded by single quotes
string2 bytes per characterStores a sequence of characters, surrounded by double quotes

2.1 Type Casting

In C#, there are two types of casting:

3. Operators

Arithmetic operators

OperatorNameDescriptionExample
+AdditionAdds together two valuesx + y
-SubtractionSubtracts one value from anotherx - y
*MultiplicationMultiplies two valuesx * y
/DivisionDivides one value by anotherx / y
%ModulusReturns the division remainderx % y
++IncrementIncreases the value of a variable by 1x++
--DecrementDecreases the value of a variable by 1x--

Assignment operators:

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

Comparison operators

OperatorNameExample
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Logical Operators

OperatorNameDescriptionExample
&&Logical andReturns True if both statements are truex < 5 && x < 10
||Logical orReturns True if one of the statements is truex < 5 || x < 4
!Logical notReverse the result, returns False if the result is true!(x < 5 && x < 10)

4. Flow Control

4.1 If-else

If-else if :

if (condition1)
{
  // block of code to be executed if condition1 is True
} 
else if (condition2) 
{
  // block of code to be executed if the condition1 is false and condition2 is True
} 
else
{
  // block of code to be executed if the condition1 is false and condition2 is False
}

4.2 Switch

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

4.3 Loop

While

while (condition) 
{
  // code block to be executed
}

Do-while

do 
{
  // code block to be executed
}
while (condition);

For

for (statement 1; statement 2; statement 3) 
{
  // code block to be executed
}

Foreach

foreach (type variableName in arrayName) 
{
  // code block to be executed
}

5. Array

To declare a array, define the variable type with square brackets:

string[] cars;
string[] names {"A", "B"};
Console.WriteLine(names[0]); // access array element
Console.WriteLine(names.Length); // get length of array

6. Method

class Program
{
  static void MyMethod(parameters declaration) 
  {
    // code to be executed
  }
}

static void Main(string[] args)
{
  MyMethod(parameters);
}

It is good practice to start with an uppercase letter when naming methods.

6.1 Default Method Value

static void MyMethod(string country = "Norway") 
{
  Console.WriteLine(country);
}

static void Main(string[] args)
{
  MyMethod("Sweden");
  MyMethod("India");
  MyMethod();
  MyMethod("USA");
}

// Sweden
// India
// Norway
// USA

6.2 Named Arguments

static void MyMethod(string child1, string child2, string child3) 
{
  Console.WriteLine("The youngest child is: " + child3);
}

static void Main(string[] args)
{
  MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}

// The youngest child is: John

6.3 Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)

7. OOP

7.1 Class

class ClassName 
{
  // Class Members
  // fields
  type fieldName = value;
  // methods
  public void MethodName(...) 
  {
      //...
  }
    
  public static void StaticMethodName(...)
  {
      //...
  }
}

Fields and methods inside classes are referred to as “Class Members”.

Objects

class Car 
{
  string color = "red";

  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.color);
  }
}

use new to create objects.

Constructor

A special method to initialize objects.

// Create a Car class
class Car
{
  public string model;  // Create a field

  // Create a class constructor for the Car class
  public Car()
  {
    model = "Mustang"; // Set the initial value for model
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();  // Create an object of the Car Class (this will call the constructor)
    Console.WriteLine(Ford.model);  // Print the value of model
  }
}

// Outputs "Mustang"

7.2 Access Modifiers

ModifierDescription
publicThe code is accessible for all classes
privateThe code is only accessible within the same class
protectedThe code is accessible within the same class, or in a class that is inherited from that class.
internalThe code is only accessible within its own assembly, but not from another assembly.

7.3 Properties And Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

class Person
{
  private string name; // field

  public string Name   // property
  {
    get { return name; }   // get method
    set { name = value; }  // set method
  }
}

Automatic Properties

class Person
{
  public string Name  // property
  { get; set; }
}

class Program
{
  static void Main(string[] args)
  {
    Person myObj = new Person();
    myObj.Name = "Liam";
    Console.WriteLine(myObj.Name);
  }
}

7.4 Inheritance

It’s possible to inherit fields and methods from one class to another, and “inheritance concept” can grouped into 2 categories:

Use : to inherit from a class :

class Vehicle  // base class (parent) 
{
  public string brand = "Ford";  // Vehicle field
  public void honk()             // Vehicle method 
  {                    
    Console.WriteLine("Tuut, tuut!");
  }
}

class Car : Vehicle  // derived class (child)
{
  public string modelName = "Mustang";  // Car field
}

class Program
{
  static void Main(string[] args)
  {
    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (From the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
    Console.WriteLine(myCar.brand + " " + myCar.modelName);
  }
}

7.5 Polymorphism

class Animal  // Base class (parent) 
{
  public void animalSound() 
  {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig : Animal  // Derived class (child) 
{
  public void animalSound() 
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Dog : Animal  // Derived class (child) 
{
  public void animalSound() 
  {
    Console.WriteLine("The dog says: bow wow");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object

    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

output:

The animal makes a sound
The animal makes a sound
The animal makes a sound

The output from the example above was probably not what you expected. That is because the base class method overrides the derived class method, when they share the same name.

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:

class Animal  // Base class (parent) 
{
  public virtual void animalSound() 
  {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig : Animal  // Derived class (child) 
{
  public override void animalSound() 
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Dog : Animal  // Derived class (child) 
{
  public override void animalSound() 
  {
    Console.WriteLine("The dog says: bow wow");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object

    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}
The animal makes a sound
The pig says: wee wee
The dog says: bow wow

7.6 Abstract Classes and Methods

The abstract keyword is used for classes and methods:

abstract class Animal 
{
  public abstract void animalSound();
  public void sleep() 
  {
    Console.WriteLine("Zzz");
  }
}

7.7 Interface

Interface can only contain abstract methods and properties.

// Interface
interface IAnimal 
{
  void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface
class Pig : IAnimal 
{
  public void animalSound() 
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
  }
}

7.8 Enum

An enum is special class that represents a group of constants.

enum Level 
{
  Low,
  Medium,
  High
}
// ...
Level myVar = Level.Medium;
Console.WriteLine(myVar);

Enum inside Class

class Program
{
  enum Level
  {
    Low,
    Medium,
    High
  }
  static void Main(string[] args)
  {
    Level myVar = Level.Medium;
    Console.WriteLine(myVar);
  }
}

Enum values

By default, the first item of an enum has the value 0, the second is 1 and so on.

enum Months
{
  January,    // 0
  February,   // 1
  March,      // 2
  April,      // 3
  May,        // 4
  June,       // 5
  July,       // 6
  Sept = 9	  // you can set specific value	
}

static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

Enum with Switch

enum Level 
{
  Low,
  Medium,
  High
}

static void Main(string[] args) 
{
  Level myVar = Level.Medium;
  switch(myVar) 
  {
    case Level.Low:
      Console.WriteLine("Low level");
      break;
    case Level.Medium:
       Console.WriteLine("Medium level");
      break;
    case Level.High:
      Console.WriteLine("High level");
      break;
  }
}

Reference

  1. C# Tutorialopen in new window W3schools
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.2