Skip to content

C# Language Basics

Posted on:August 19, 2023 at 10:20 PM

Table of contents

Open Table of contents

🥝C#

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/

1. Basic program structure


using System;

namespace Azure{
	class AzureService{
		static public void Main(string[] args){}
	}
}

2. DataType

Base Types

child_database

Reference Type

object = System.Object

dynamic

string = System.String

@quoted

Pointer Type

3. Type conversion

implicit type conversion

explicit type conversion

Built-in Conversion Methods

4. Console Interaction

5. Operations

Miscellaneous operations

6. Encapsulation

Access Specifier

7. Nullable Identifiers

8. Array

https://www.tutorialspoint.com/csharp/csharp_arrays.htm

9. Structure

10. Enum

enum ENUM_NAME{
	enumeration list
}

11. Polymorphism

Overwritten

12. Operator Method

public static Box operator+ (Box b, Box c) {
   Box box = new Box();
   box.length = b.length + c.length;
   box.breadth = b.breadth + c.breadth;
   box.height = b.height + c.height;
   return box;
}

// application
Box a = new Box(1,2,3);
Box b = new Box(5,6,7);
a + b // Box(6,8,10)

13. Interface

syntactical contract

namespace InterfaceApplication {
	public interface ITransaction {
		void showTransaction();
	}

	public class StockTransaction : ITransaction {
		public void showTransaction(){ ... }
	}

	public class FundTransaction {
		public void showTransaction(){ ... }
	}
}

14. Namespace

Namespaces can be nested.

namespace father {
	namespace child {
	}
}

15. 🔺Preprocessor

child_database

16. Exception handler

Syntax

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
	 throw(new System.IO.IOException("Raise IO Exception"))
} finally {
   // statements to be executed
}

17. I/O

stream

C# MS docs

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.

field ⇒ 变量 variable

public override string ToString() => "This is an object";

Parameter types of method

Ref parameter

static void Swap(ref int x, ref int y)
{
	int temp = x;
	x = y;
	y = temp;
}

Output parameter

static void Divide(int x, int y, out int result, out int remainder)
{
    result = x / y;
    remainder = x % y;
}

public static void OutUsage()
{
    Divide(10, 3, out int res, out int rem);
    Console.WriteLine($"{res} {rem}");	// "3 1"
}

Parameter array

public class Console
{
    public static void Write(string fmt, params object[] args) { }
    public static void WriteLine(string fmt, params object[] args) { }
    // ...
}

Constructor

Finalizer

Property

public class PropertyClass
{
	private int _volumn = 100;
	public int Volumn
	{
		get => _volumn;
		set
		{
			if (value < 0)
			{
				_volumn = 0;
			}
			else if (value > 100)
			{
				_volumn = 100;	
			}
			else
			{
				_volumn = value;
			}
		}
	}
}

Indexers

public T this[int index]
{
    get => _items[index];
    set
    {
        _items[index] = value;
        OnChanged();
    }
}

Events

class EventTest
{
	private int _val;
	public int val
	{
		set
		{
			_val = value;
			onChanged();
		}
		get
		{
			return _val;
		}
	}

	protect virtual void OnChanged() 
	{
		Changed?.invoke(this, EventArgs.Empty)
	}

	public event EventHandler Changed
	{
		add
		{
		}
		
		remove
		{
		}
	}
}

// Main
EventTest test = new EventTest();
test.Changed += new EventHandler( () => {} )

Operators

// class scope
public static bool operator == (T a, T b) => a.val == b.val;

Finalizer

class Car
{
	Car() {} // constructor
	~Car() {} // deconstructor
}

virtual vs. abstract

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

”⇒” in C#

bookmark

Statements

LINQ: Language-Integrated Query

https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=net-5.0

https://github.com/dotnet/try-samples/blob/main/101-linq-samples

Delegate

public delegate int PerformCalculation(int x, int y);

Convert and Parse

Record vs Class

bookmark

public record Person(string FirstName, string LastName);

public record Person(string FirstName, string LastName)
{
    public string[] PhoneNumbers { get; init; }
}

public static void Main()
{
    Person person1 = new("Nancy", "Davolio") { PhoneNumbers = new string[1] };
    Console.WriteLine(person1);
    // output: Person { FirstName = Nancy, LastName = Davolio, PhoneNumbers = System.String[] }

    Person person2 = person1 with { FirstName = "John" };
    Console.WriteLine(person2);
    // output: Person { FirstName = John, LastName = Davolio, PhoneNumbers = System.String[] }
    Console.WriteLine(person1 == person2); // output: False

    person2 = person1 with { PhoneNumbers = new string[1] };
    Console.WriteLine(person2);
    // output: Person { FirstName = Nancy, LastName = Davolio, PhoneNumbers = System.String[] }
    Console.WriteLine(person1 == person2); // output: False

    person2 = person1 with { };
    Console.WriteLine(person1 == person2); // output: True
}

Anonymous Type

bookmark

OmniSharp: intellisense

used for generate code map → grammar compiler

https://github.com/OmniSharp

Roslyn

https://github.com/dotnet/roslyn

Important Feature

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/features

Runtime

  1. System.Action

use (context, config)=>{METHOD}

Untitled.png

Untitled.png

delegate相当于声明一个固定的函数类型的指针

  1. Attributes & Reflection
  1. UnitTest using MSTest

https://docs.microsoft.com/en-us/visualstudio/test/using-microsoft-visualstudio-testtools-unittesting-members-in-unit-tests?view=vs-2019

  1. System.Linq.Expression

Untitled.png

Dependency Inversion

https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/architectural-principles#dependency-inversion

Lazy Initializer

Singleton Design in C#

  1. basic c# singleton impletation

https://csharpindepth.com/articles/singleton

  1. diffs btw singleton and static?

https://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern

  1. heap and stack — memory allocation