Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C# Language Specification Support #819

Open
Jim8y opened this issue Nov 15, 2023 · 1 comment
Open

C# Language Specification Support #819

Jim8y opened this issue Nov 15, 2023 · 1 comment
Assignees

Comments

@Jim8y
Copy link
Contributor

Jim8y commented Nov 15, 2023

C# Language Specification Support

Although Neo claims that smart contract development can be done using C#, the issue is that Neo does not support all C# syntax rules. This often creates confusion for C# developers, as they are not aware of which syntaxes are supported and which are not. Moreover, since C# itself is not designed for smart contract development, some syntaxes may behave inconsistently when developing contracts. To address this issue, I suggest that we initially use the standard of the C# language as our benchmark for contract development. Based on the C# standard, we should try to support a more complete C# syntax for contract development as much as possible. For those C# syntax features that are inconsistent or unsupported, we need to have clear documentation to introduce them.

C# Language Specification : https://ecma-international.org/publications-and-standards/standards/ecma-334/

C# Syntax Reference

1. Keywords

Basic Data Types (https://github.com/neo-project/neo-devpack-dotnet/blob/master/src/Neo.Compiler.CSharp/Helper.cs)

  • void: Represents the absence of a value or a method that does not return a value.
  • bool: Declares a variable of Boolean data type. Example: bool isReady = true;
  • byte: Declares a variable of 8-bit unsigned integer data type. Example: byte myByte = 100;
  • char: Declares a variable of character data type. Example: char myChar = 'A';
  • decimal: Declares a variable of decimal data type. Example: decimal price = 19.99M;
  • double: Declares a variable of double-precision floating-point data type. Example: double pi = 3.14159265359;
  • float: Declares a variable of single-precision floating-point data type. Example: float price = 19.99F;
  • int: Declares a variable of 32-bit signed integer data type. Example: int count = 10;
  • long: Declares a variable of 64-bit signed integer data type. Example: long bigNumber = 1234567890L;
  • sbyte: Declares a variable of 8-bit signed integer data type. Example: sbyte smallNumber = -128;
  • short: Declares a variable of 16-bit signed integer data type. Example: short smallValue = 32767;
  • uint: Declares a variable of 32-bit unsigned integer data type. Example: uint positiveValue = 123;
  • ulong: Declares a variable of 64-bit unsigned integer data type. Example: ulong bigPositiveValue = 1234567890UL;
  • ushort: Declares a variable of 16-bit unsigned integer data type. Example: ushort smallPositiveValue = 65535;
  • string: Declares a variable of string data type. Example: string text = "Hello, world!";
  • object: Declares a variable of object data type. Example: object myObject = new MyType();
  • System.Numerics.BigInteger: Represents a large integer data type. Example: System.Numerics.BigInteger bigInt = 1234567890123456789012345678901234567890;
  • List: Represents a list data type. Example: List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
  • Map: Represents a map data type. Example: Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();
  • Neo.UInt160: Represents a 160-bit unsigned integer data type. Example: Neo.UInt160 hash160Value = new Neo.UInt160();
  • Neo.UInt256: Represents a 256-bit unsigned integer data type. Example: Neo.UInt256 hash256Value = new Neo.UInt256();

C# to Neo smart contract type mapping table:

C# Type Neo Type Description
bool Boolean Boolean type
byte Integer 8-bit unsigned integer
sbyte Integer 8-bit signed integer
short Integer 256-bit signed integer-le
ushort Integer 256-bit signed integer-le
int Integer 256-bit signed integer-le
uint Integer 256-bit signed integer-le
long Integer 256-bit signed integer-le
ulong Integer 256-bit signed integer-le
char Integer Unicode character
string ByteString String
byte[] ByteArray Byte array
BigInteger Integer 256-bit signed integer
Enum types Integer Enum underlying integer mapping
Array types Array Array
object Any Any type
void Void No return value
Neo.Cryptography.ECC.ECPoint PublicKey Represents public key
Neo.SmartContract.Framework.ByteString ByteString Byte string
Neo.UInt160 Hash160 20-byte hash value
Neo.UInt256 Hash256 32-byte hash value
Other classes/interfaces ByteArray Stored as byte arrays

Classes and Structures

  • class: Declares a class. Example: class MyClass { }
  • struct: Declares a value type. Example: struct Point { public int X; public int Y; }
  • enum: Declares an enumeration. Example: enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • delegate: Declares a delegate. Example: delegate int MyDelegate(int x, int y);
  • interface: Declares an interface. Example: interface IMyInterface { /* interface members */ }

Control Flow Keywords (https://github.com/neo-project/neo-devpack-dotnet/blob/master/src/Neo.Compiler.CSharp/MethodConvert.cs)

  • if: Starts an if statement. Example: if (condition) { /* code */ }
  • else: Defines an alternative branch in an if statement. Example: if (condition) { /* true branch */ } else { /* else branch */ }
  • switch: Starts a switch statement. Example: switch (dayOfWeek) { case DayOfWeek.Monday: /* code */ break; }
  • case: Defines individual cases in a switch statement. Example: switch (dayOfWeek) { case DayOfWeek.Monday: Console.WriteLine("It's Monday."); break; }
  • default: Specifies the default case in a switch statement. Example: switch (dayOfWeek) { default: Console.WriteLine("It's another day."); break; }
  • for: Starts a for loop. Example: for (int i = 0; i < 10; i++) { /* loop body */ }
  • foreach: Iterates over elements in a collection. Example: foreach (var item in myList) { /* process item */ }
  • while: Starts a while loop. Example: while (condition) { /* loop body */ }
  • do: Starts a do-while loop. Example: do { /* loop body */ } while (condition);
  • break: Exits a loop or switch statement prematurely. Example: for (int i = 0; i < 10; i++) { if (i == 5) break; }
  • continue: Jumps to the next iteration of a loop. Example: for (int i = 0; i < 10; i++) { if (i == 5) continue; }
  • goto: Transfers control to a labeled statement. Example: `goto MyLabel
  • return: Returns a value from a method. Example: public int MyMethod() { return 42; }
  • throw: Throws an exception. Example: throw new Exception("An error occurred.");
  • try: Starts a try-catch block. Example: try { /* code */ } catch (Exception ex) { /* handle exception */ }
  • catch: Catches and handles exceptions in a try-catch block. Example: try { /* code that may throw an exception */ } catch (Exception ex) { /* handle exception */ }
  • finally: Defines a block of code to be executed in a try-catch-finally block. Example: try { /* code */ } catch (Exception ex) { /* handle exception */ } finally { /* cleanup code */ }

Access Modifiers and Member Control

  • public: Specifies access for a class or member to any code. Example: public class MyClass { }
  • private: Restricts access to a class or member. Example: private int myField;
  • protected: Specifies access for a class or member within the same class or derived classes. Example: protected void MyMethod() { /* code */ }
  • internal: Specifies that a class or member is accessible within the same assembly. Example: internal class MyInternalClass { }
  • static: Declares a static member. Example: public static void MyMethod() { /* code */ }
  • readonly: Declares a read-only field. Example: public readonly int MaxValue = 100;
  • const: Declares a constant. Example: const int MaxValue = 100;
  • volatile: Specifies that a field may be modified by multiple threads. Example: private volatile int counter;
  • abstract: Used to declare abstract classes or methods. Example: abstract class Shape { }
  • sealed: Prevents a class from being inherited. Example: sealed class MySealedClass { }
  • override: Overrides a base class member in a derived class. Example: public override void MyMethod() { /* code */ }
  • virtual: Declares a virtual member that can be overridden. Example: public virtual void MyMethod() { /* code */ }
  • extern: Indicates that a method is implemented externally. Example: extern void NativeMethod();

Type Conversion and Checking

  • as: Used for type casting or conversion. Example: object obj = "Hello"; string str = obj as string;
  • is: Checks if an object is of a specified type. Example: if (myObject is MyClass) { /* code */ }
  • typeof: Gets the Type object for a type. Example: Type type = typeof(MyClass);
  • sizeof: Gets the size of an unmanaged type. Example: int size = sizeof(int);
  • checked: Enables overflow checking for arithmetic operations. Example: checked { int result = int.MaxValue + 1; }
  • unchecked: Disables overflow checking for arithmetic operations. Example: unchecked { int result = int.MaxValue + 1; }
  • implicit: Defines an implicit user-defined type conversion operator. Example: public static implicit operator MyType(int value) { /* conversion logic */ }
  • explicit: Defines a user-defined type conversion operator. Example: public static explicit operator int(MyClass myObj) { /* conversion logic */ }

Parameters and Methods

  • ref: Passes a parameter by reference. Example: public void MyMethod(ref int value) { /* code */ }
  • out: Indicates that a parameter is passed by reference. Example: public void MyMethod(out int result) { /* code */ }
  • params: Specifies a variable-length parameter list. Example: public void MyMethod(params int[] numbers) { /* code */ }
  • this: Refers to the current instance of a class. Example: this.myField = 42;
  • base: Used to access members of the base class. Example: base.MethodName();
  • new: Creates an object or hides a member. Example: new MyType();

Special Keywords

  • operator: Declares an operator. Example: public static MyType operator +(MyType a, MyType b) { /* operator logic */ }
  • event: Declares an event. Example: public event EventHandler MyEvent;
  • lock: Defines a synchronized block of code. Example: lock (myLockObject) { /* code */ }
  • fixed: Specifies a pointer to a fixed memory location. Example: fixed (int* ptr = &myVariable) { /* code */ }
  • unsafe: Allows the use of unsafe code blocks. Example: unsafe { /* unsafe code */ }
  • in: Specifies the iteration variable in a foreach loop. Example: foreach (var item in myCollection) { /* code */ }
  • null: Represents a null value. Example: object obj = null;
  • true: Represents the Boolean true value. Example: bool isTrue = true;
  • false: Represents the Boolean false value. Example: bool isTrue = false;
  • stackalloc: Allocates memory on the stack. Example: int* stackArray = stackalloc int[100];
  • using: Defines a scope for a resource and ensures its disposal. Example: using (var resource = new MyResource()) { /* code */ }

Contextual Keywords

  • add: Used in property declarations to add an event handler. Example:

    public event EventHandler MyEvent
    {
        add { /* Logic to add event handler */ }
        remove { /* Logic to remove event handler */ }
    }
  • alias: Used to provide a namespace or type alias. Example:

    using MyAlias = MyNamespace.MyLongNamespaceName;
  • ascending: Used in LINQ queries to specify ascending sorting. Example:

    var sortedNumbers = numbers.OrderBy(x => x);
  • async: Marks a method as asynchronous.

    Example:

    public async Task MyAsyncMethod()
    {
        // Asynchronous operation
    }
  • await: Suspends the execution of an asynchronous method until the awaited task completes. Example:

    async Task MyMethodAsync()
    {
        int result = await SomeAsyncOperationAsync();
        // Continue with subsequent operations
    }
  • by: Used in a join clause in LINQ queries to specify the join condition. Example:

    var query = from person in people
                join city in cities on person.CityId equals city.Id
                select new { person.Name, city.CityName };
  • descending: Used in LINQ queries to specify descending sorting. Example:

    var sortedNumbers = numbers.OrderByDescending(x => x);
  • dynamic: Declares a dynamic type that bypasses compile-time type checking. Example:

    dynamic dynamicVar = 42;
    Console.WriteLine(dynamicVar); // Outputs 42
  • equals: Used in pattern matching to check if a value matches a specified pattern. Example:

    if (value is 42 equals int intValue)
    {
        // If the value equals 42, cast it to an int intValue
    }
  • from: Used in LINQ queries to specify the data source. Example:

    var query = from person in people
                select person.Name;
  • get: Defines a property's getter method. Example:

    public int MyProperty
    {
        get { return myField; }
    }
  • global: Used to reference items from the global namespace. Example:

    global::System.Console.WriteLine("Hello, world!");
  • group: Used in a group by clause in LINQ queries. Example:

    var query = from person in people
                group person by person.City into cityGroup
                select new { City = cityGroup.Key, Count = cityGroup.Count() };
  • into: Used in LINQ queries to create a new range variable. Example:

    var query = from person in people
                group person by person.City into cityGroup
                where cityGroup.Count() > 2
                select new { City = cityGroup.Key, Count = cityGroup.Count() };
  • join: Used in LINQ queries to perform a join operation. Example:

    var query = from person in people
                join city in cities on person.CityId equals city.Id
                select new { person.Name, city.CityName };
  • let: Used in a let clause in LINQ queries to define a new variable. Example:

    var query = from person in people
                let fullName = $"{person.FirstName} {person.LastName}"
                select fullName;
  • nameof: Returns the name of a variable, type, or member as a string. Example:

    string propertyName = nameof(MyClass.MyProperty);
  • on: Used in a join clause in LINQ queries to specify the join condition. Example:

    var query = from person in people
                join city in cities
                on new { person.CityId, person.CountryId }
                equals new { city.CityId, city.CountryId }
                select new { person.Name, city.CityName };
  • orderby: Used in LINQ queries to specify sorting. Example:

    var sortedNumbers = numbers.OrderBy(x => x);
  • partial: Indicates that a class, struct, or interface is defined in multiple files. Example:

    partial class MyClass
    {
        // Definition in the first file
    }
  • remove: Used in property declarations to remove an event handler. Example:

    public event EventHandler MyEvent
    {
        remove { /* Logic to remove event handler */ }
    }
  • select: Used in LINQ queries to specify the projection. Example:

    var query = from person in people
                select new { person.Name, person.Age };
  • set: Defines a property's setter method. Example:

    public int MyProperty
    {
        set { myField = value; }
    }
  • unmanaged: Used to specify an unmanaged generic type constraint. Example:

    public void MyMethod<T>() where T : unmanaged
    {
        // Implementation of the generic method
    }
  • value: Refers to the value of a property or indexer within a property or indexer accessor. Example:

    public int MyProperty
    {
        get { return myField; }
        set { myField = value; }
    }
  • var: Declares an implicitly typed local variable. Example:

    var number = 42;
  • when: Used in a catch clause to specify an exception filter. Example:

    try
    {
        // Code block
    }
    catch (Exception ex) when (ex.InnerException != null)
    {
        // Exception filter
    }
  • where: Used in LINQ queries to specify filtering criteria. Example:

    var query = from person in people
                where person.Age > 18
                select person.Name;
  • yield: Used to return values from an iterator method. Example:

    public IEnumerable<int> GetNumbers()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }

2. Operators (https://github.com/neo-project/neo-devpack-dotnet/blob/master/src/Neo.Compiler.CSharp/MethodConvert.cs)

Arithmetic Operators

  • +: Adds two operands. Example: int result = 5 + 3; // result is 8
  • -: Represents subtraction when used between two numeric values, such as x - y. Example: int result = 10 - 5; // result is 5
  • -: Represents the negation operator when used as a unary operator before a numeric value to make it negative, such as -x. Example: int negativeValue = -10; // negativeValue is -10
  • *: Multiplies two operands. Example: int result = 7 * 2; // result is 14
  • /: Divides the first operand by the second. Example: int result = 16 / 4; // result is 4
  • %: Returns the remainder of the division. Example: int result = 17 % 5; // result is 2

Comparison Operators

  • ==: Checks if two values are equal. Example: bool isEqual = (x == y);
  • !=: Checks if two values are not equal. Example: bool isNotEqual = (x != y);
  • <: Checks if the first value is less than the second. Example: bool isLess = (x < y);
  • >: Checks if the first value is greater than the second. Example: bool isGreater = (x > y);
  • <=: Checks if the first value is less than or equal to the second. Example: bool isLessOrEqual = (x <= y);
  • >=: Checks if the first value is greater than or equal to the second. Example: bool isGreaterOrEqual = (x >= y);

Logical Operators

  • &&: Logical AND operator. Returns true if both operands are true. Example: bool result = (x && y);
  • ||: Logical OR operator. Returns true if at least one operand is true. Example: bool result = (x || y);
  • !: Logical NOT operator. Inverts the value of the operand. Example: bool result = !x;

Bitwise Operators

  • &: Bitwise AND operator. Performs a bitwise AND operation between two integers. Example: int result = x & y;
  • |: Bitwise OR operator. Performs a bitwise OR operation between two integers. Example: int result = x | y;
  • ^: Bitwise XOR operator. Performs a bitwise XOR operation between two integers. Example: int result = x ^ y;
  • ~: Bitwise NOT operator. Inverts the bits of an integer. Example: int result = ~x;
  • <<: Left shift operator. Shifts the bits of an integer to the left. Example: int result = x << 2;
  • >>: Right shift operator. Shifts the bits of an integer to the right. Example: int result = x >> 2;

Assignment Operators

  • =: Assigns the value of the right operand to the left operand. Example: x = 10;
  • +=: Adds the right operand to the left operand and assigns the result. Example: x += 5;
  • -=: Subtracts the right operand from the left operand and assigns the result. Example: x -= 3;
  • *=: Multiplies the left operand by the right operand and assigns the result. Example: x *= 2;
  • /=: Divides the left operand by the right operand and assigns the result. Example: x /= 4;
  • %=: Calculates the remainder of the left operand divided by the right operand and assigns the result. Example: x %= 3;
  • &=: Performs a bitwise AND operation between the left and right operands and assigns the result. Example: x &= y;
  • |=: Performs a bitwise OR operation between the left and right operands and assigns the result. Example: x |= y;
  • ^=: Performs a bitwise XOR operation between the left and right operands and assigns the result. Example: x ^= y;
  • <<=: Shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result. Example: x <<= 3;
  • >>=: Shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result. Example: x >>= 2;
  • ??=: Assigns the value of the right operand to the left operand only if the left operand is null. Example: x ??= defaultValue;

Other Operators

  • ??: Null coalescing operator. Returns the left operand if it is not null; otherwise, returns the right operand. Example: string result = x ?? "default";
  • ?.: Null-conditional operator. Allows accessing members of an object if the object is not null. Example: int? length = text?.Length;
  • ?:: Ternary conditional operator. Returns one of two values based on a condition. Example: int result = (condition) ? x : y;
  • =>: Lambda operator. Used to define lambda expressions. Example: (x, y) => x + y
  • ++: Increment operator. Increases the value of a variable by 1. Example: x++;
  • --: Decrement operator. Decreases the value of a variable by 1. Example: x--;
  • ->: Pointer member access operator. Used in unsafe code to access members of a structure or class through a pointer. Example in unsafe code: ptr->member;

3. Data Types

Value Types

  • int: Represents a 32-bit signed integer. Example: int number = 42;
  • long: Represents a 64-bit signed integer. Example: long bigNumber = 1234567890L;
  • float: Represents a single-precision floating-point number. Example: float price = 19.99F;
  • double: Represents a double-precision floating-point number. Example: double pi = 3.14159265359;
  • decimal: Represents a decimal number with high precision. Example: decimal price = 19.99M;
  • char: Represents a Unicode character. Example: char letter = 'A';
  • bool: Represents a Boolean value (true or false). Example: bool isTrue = true;
  • byte: Represents an 8-bit unsigned integer. Example: byte smallNumber = 100;
  • sbyte: Represents an 8-bit signed integer. Example: sbyte smallNumber = -128;
  • short: Represents a 16-bit signed integer. Example: short smallValue = 32767;
  • ushort: Represents a 16-bit unsigned integer. Example: ushort smallPositiveValue = 65535;
  • uint: Represents a 32-bit unsigned integer. Example: uint positiveValue = 123;
  • ulong: Represents a 64-bit unsigned integer. Example: ulong bigPositiveValue = 1234567890UL;
  • enum: Represents an enumeration. Example: enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • struct: Represents a value type. Example: struct Point { public int X; public int Y; }

Reference Types

  • string: Represents a sequence of characters. Example: string text = "Hello, world!";
  • object: Represents a base type for all types in C#. Example: object obj = new MyType();
  • class: Represents a reference type (class definition). Example: class MyClass { }
  • interface: Represents an interface. Example: interface IMyInterface { /* interface members */ }
  • delegate: Represents a delegate. Example: delegate int MyDelegate(int x, int y);
  • dynamic: Represents a dynamically-typed object. Example: dynamic dynVar = 42;
  • array: Represents an array. Example: int[] numbers = { 1, 2, 3, 4, 5 };

4. Syntactic Sugar and Advanced Features

  • Auto Properties: Used to simplify property declaration with getter and setter methods. Example: public int MyProperty { get; set; }
  • Object and Collection Initializers: Allow concise initialization of objects and collections. Example:
    var person = new Person
    {
        FirstName = "John",
        LastName = "Doe",
        Age = 30
    };
  • String Interpolation: Provides a more readable way to format strings with embedded expressions. Example: string name = $"Hello, {firstName} {lastName}!";
  • Anonymous Types: Allow the creation of objects with dynamically defined properties. Example: var person = new { Name = "John", Age = 30 };
  • Lambda Expressions: Enable the creation of inline delegate functions. Example: (x, y) => x + y
  • LINQ Queries: Provide a language-integrated query syntax for collections. Example:
    var result = from num in numbers
                 where num % 2 == 0
                 select num;
  • Extension Methods: Allow adding new methods to existing types without modifying them. Example: public static string Reverse(this string str) { /* code */ }
  • Generics: Enable type parameterization to create reusable data structures and algorithms. Example: public class List<T> { /* code */ }
  • Asynchronous Programming (async, await): Facilitate non-blocking code execution. Example:
    public async Task<int> GetDataAsync()
    {
        // asynchronous code
    }
  • Pattern Matching: Simplify conditional code with pattern-based matching. Example:
    if (obj is string text)
    {
        // code using 'text' as a string
    }
  • Tuples: Allow grouping multiple values into a single entity. Example: (int, string) result = (42, "Hello");
  • Local Functions: Define functions within a method for local scope. Example:
    int CalculateSum(int a, int b)
    {
        int Add() => a + b;
        return Add();
    }
  • Record Types (C# 9.0+): Simplify the creation of classes for holding data. Example:
    public record Person(string FirstName, string LastName);
  • Nullable Reference Types (C# 8.0+): Enhance null safety by introducing nullable annotations. Example: string? nullableString = null;
  • Ranges and Indices (C# 8.0+): Allow slicing and indexing collections with a more expressive syntax. Example: var subArray = myArray[1..4];

5. Other Features

  • Properties and Indexers: Provide access to class members with getter and setter methods. Example: public int MyProperty { get; set; }
  • Delegates and Events: Enable the creation of delegate types and event handlers. Example:
    public delegate void MyDelegate(string message);
    public event MyDelegate MyEvent;
  • Exception Handling: Allows catching and handling exceptions in code. Example:
    try
    {
        // code that may throw an exception
    }
    catch (Exception ex)
    {
        // handle exception
    }
  • Reflection: Provides information about types and objects at runtime. Example:
    Type type = typeof(MyClass);
    MethodInfo method = type.GetMethod("MyMethod");
  • Attributes: Add metadata to code elements. Example:
    [Obsolete("This method is obsolete. Use NewMethod instead.")]
    public void OldMethod()
    {
        // code
    }
  • Namespaces: Organize code into logical groupings. Example: namespace MyNamespace { /* code */ }
  • Threads and Concurrency: Manage concurrent execution using threads and tasks. Example:
    Task.Run(() =>
    {
        // code to run asynchronously
    });
  • Memory Management and Pointers: Allow low-level memory manipulation using pointers (unsafe code). Example:
    unsafe
    {
        int* ptr = &myVariable;
        // code using pointer
    }
  • File and Stream Operations: Provide functionality for working with files and streams. Example:
    using (var stream = File.OpenRead("file.txt"))
    {
        // code to read from stream
    }
  • Network Programming: Enable communication over networks. Example:
    using (var client = new TcpClient())
    {
        // code for network communication
    }

6. Compilation Directives and Special Symbols

Compilation Directives

  • #if: Conditional compilation based on preprocessor symbols.
  • #else: Specifies alternative code for #if conditions.
  • #elif: Specifies additional conditions for #if blocks.
  • #endif: Ends conditional compilation blocks.
  • #define: Defines preprocessor symbols.
  • #undef: Undefines preprocessor symbols.
  • #warning: Generates a warning message.
  • #error: Generates an error message.
  • #line: Specifies line number and file name information.
  • #region: Marks the start of a collapsible code region.
  • #endregion: Marks the end of a collapsible code region.
  • #nullable: Specifies nullability annotations.

Special Symbols

  • @ (Used for non-escaped strings or keywords as identifiers)

Numeric Type Conversions:

  • int to long
  • int to double
  • float to double
  • short to int
  • byte to int
  • decimal to double
  • char to int
    String Conversions:
  • string to int
  • string to double
  • string to DateTime
  • string to bool
    Boolean Conversions:
  • bool to int (1 for true, 0 for false)
  • bool to string
    Enum Conversions:
  • Enum to its underlying numeric type (e.g., enum to int)
  • Numeric type to an enum (e.g., int to enum)
    Nullable Types:
  • Converting between nullable and non-nullable versions of value types (e.g., int? to int)
  • Converting between nullable types (e.g., int? to double?)
    Array Conversions:
  • Converting between arrays of different types (e.g., int[] to double[])
    Object Conversions:
  • Converting between an object and a specific type (e.g., object to string)
    Casting and Explicit Conversions:
  • Using explicit casting operators to convert between types (e.g., (int)doubleValue)
  • Using explicit casting for custom types or class objects
    DateTime Conversions:
  • Converting DateTime to string (and vice versa) in various formats
  • Extracting date or time components from DateTime objects
    Custom Type Conversions (User-Defined):
  • Defining custom conversion operators for user-defined types (e.g., converting between custom classes)
    Base Type Conversions:
  • Converting between derived and base class objects (polymorphism)
    Implicit and Explicit Interface Implementations:
  • Implementing interfaces and converting between interface types

Common Mathematical Methods and Functions in C#

Basic Arithmetic Operations:

  • Math.Add(x, y): Adds two numbers x and y.
  • Math.Subtract(x, y): Subtracts y from x.
  • Math.Multiply(x, y): Multiplies two numbers x and y.
  • Math.Divide(x, y): Divides x by y.

Exponentiation and Logarithms:

  • Math.Pow(x, y): Returns x raised to the power of y.
  • Math.Sqrt(x): Calculates the square root of x.
  • Math.Log(x): Returns the natural logarithm of x.
  • Math.Log10(x): Returns the base 10 logarithm of x.

Trigonometric Functions:

  • Math.Sin(x): Returns the sine of the angle x in radians.
  • Math.Cos(x): Returns the cosine of the angle x in radians.
  • Math.Tan(x): Returns the tangent of the angle x in radians.
  • Math.Asin(x): Returns the arcsine (inverse sine) in radians.
  • Math.Acos(x): Returns the arccosine (inverse cosine) in radians.
  • Math.Atan(x): Returns the arctangent (inverse tangent) in radians.
  • Math.Atan2(y, x): Returns the angle whose tangent is the quotient of y and x.

Rounding and Precision:

  • Math.Round(x): Rounds a number x to the nearest integer.
  • Math.Floor(x): Rounds x down to the nearest integer.
  • Math.Ceiling(x): Rounds x up to the nearest integer.
  • Math.Truncate(x): Truncates x to an integer by removing its fractional part.
  • Math.Round(x, decimals): Rounds x to a specified number of decimal places.

Absolute and Sign:

  • Math.Abs(x): Returns the absolute (non-negative) value of x.
  • Math.Sign(x): Returns the sign of x (-1 for negative, 0 for zero, 1 for positive).

Random Number Generation:

  • Random random = new Random(): Creating a random number generator instance.
  • random.Next(): Generates a random integer.
  • random.Next(min, max): Generates a random integer between min (inclusive) and max (exclusive).
  • random.NextDouble(): Generates a random double value between 0.0 and 1.0.

Constants:

  • Math.PI: Represents the mathematical constant π (pi).
  • Math.E: Represents the mathematical constant e (the base of natural logarithms).

Additional Functions:

  • Math.Max(x, y): Returns the larger of two numbers x and y.
  • Math.Min(x, y): Returns the smaller of two numbers x and y.
  • Math.Clamp(x, min, max): Limits the value of x to be within the range [min, max].

Common String Methods in C#

  1. String Length:
    • string.Length: Returns the length (number of characters) of a string.
  2. Substring Extraction:
    • string.Substring(startIndex): Returns a substring starting from the specified startIndex to the end of the string.
    • string.Substring(startIndex, length): Returns a substring starting from the specified startIndex with the specified length.
  3. Concatenation:
    • string.Concat(str1, str2, ...): Concatenates multiple strings together.
  4. String Interpolation:
    • $"...": Allows you to embed expressions and variables directly within a string.
  5. String Formatting:
    • string.Format(format, arg0, arg1, ...): Formats a string with placeholders and values.
  6. String Comparison:
    • string.Equals(str1, str2): Compares two strings for equality.
    • string.Compare(str1, str2): Compares two strings and returns a value indicating their relative order.
  7. String Searching and Checking:
    • string.Contains(substring): Checks if a string contains a specified substring.
    • string.StartsWith(prefix): Checks if a string starts with a specified prefix.
    • string.EndsWith(suffix): Checks if a string ends with a specified suffix.
  8. String Manipulation:
    • string.ToUpper(): Converts the string to uppercase.
    • string.ToLower(): Converts the string to lowercase.
    • string.Trim(): Removes leading and trailing whitespace.
  9. String Splitting:
    • string.Split(delimiters): Splits a string into an array of substrings based on specified delimiters.
  10. String Replacement:
    • string.Replace(oldValue, newValue): Replaces all occurrences of oldValue with newValue.
  11. String Empty or Null Check:
    • string.IsNullOrEmpty(str): Checks if a string is either null or empty.
    • string.IsNullOrWhiteSpace(str): Checks if a string is null, empty, or contains only whitespace.

Common Char Methods and Properties in C#

Character Representation

  • char c: Represents a single Unicode character.

Char Comparison

  • char.Equals(char1, char2): Compares two characters for equality.
  • char.CompareTo(char1, char2): Compares two characters and returns a value indicating their relative order.

Char Conversions

  • char.GetNumericValue(char): Converts a numeric character to its double-precision floating-point equivalent.
  • char.GetUnicodeCategory(char): Returns the Unicode category of a character.

Char Testing

  • char.IsDigit(char): Checks if a character represents a digit.
  • char.IsLetter(char): Checks if a character is a letter.
  • char.IsWhiteSpace(char): Checks if a character is whitespace.
  • char.IsLower(char): Checks if a character is lowercase.
  • char.IsUpper(char): Checks if a character is uppercase.

Char Case Conversions

  • char.ToLower(char): Converts a character to lowercase.
  • char.ToUpper(char): Converts a character to uppercase.

Common LINQ Query Methods and Operations in C#

LINQ is a powerful language feature in C# that allows you to query and manipulate collections of data. Here are some common LINQ methods and operations:

Certainly! Here's the provided content with empty checkboxes:

Query Methods

  1. Where: Filters a sequence of elements based on a given condition.

    • Example: var result = numbers.Where(x => x > 5);
  2. Select: Transforms each element of a sequence into a new form.

    • Example: var result = names.Select(name => name.ToUpper());
  3. OrderBy and OrderByDescending: Sorts elements in ascending or descending order based on a specified key.

    • Example: var result = numbers.OrderBy(x => x);
  4. GroupBy: Groups elements based on a key and returns groups of elements.

    • Example: var result = products.GroupBy(product => product.Category);
  5. Join: Combines two collections based on a common key.

    • Example: var result = customers.Join(orders, customer => customer.Id, order => order.CustomerId, (customer, order) => new { customer.Name, order.OrderDate });
  6. Any and All: Checks if any or all elements in a sequence satisfy a condition.

    • Example: bool anyPositive = numbers.Any(x => x > 0);
  7. First, FirstOrDefault, Last, and LastOrDefault: Retrieves the first or last element in a sequence, optionally with a condition.

    • Example: var firstPositive = numbers.First(x => x > 0);
  8. Single, SingleOrDefault: Retrieves the single element in a sequence that satisfies a condition.

    • Example: var singlePositive = numbers.Single(x => x > 0);

Set Operations

  1. Union: Combines two sequences, removing duplicates.

    • Example: var result = sequence1.Union(sequence2);
  2. Intersect: Returns the common elements between two sequences.

    • Example: var result = sequence1.Intersect(sequence2);
  3. Except: Returns elements that are present in one sequence but not in another.

    • Example: var result = sequence1.Except(sequence2);

Aggregation

  1. Count: Returns the number of elements in a sequence.

    • Example: int count = numbers.Count();
  2. Sum, Min, and Max: Calculates the sum, minimum, or maximum value in a sequence.

    • Example: int sum = numbers.Sum();
  3. Average: Computes the average value of elements in a sequence.

    • Example: double average = numbers.Average();
  4. Aggregate: Performs a custom aggregation operation on elements in a sequence.

    • Example: var result = numbers.Aggregate((x, y) => x * y);

Conversion

  1. ToList and ToArray: Converts a sequence to a list or an array.

    • Example: List<int> list = numbers.ToList();
  2. ToDictionary: Converts a sequence into a dictionary based on key and value selectors.

    • Example: Dictionary<int, string> dict = items.ToDictionary(item => item.Id, item => item.Name);
  3. OfType: Filters elements of a sequence to include only those of a specific type.

    • Example: var result = mixedObjects.OfType<string>();
  4. Cast: Casts elements of a sequence to a specified type.

    • Example: var result = mixedObjects.Cast<int>();

Valid C# Statements

  1. Variable Declaration and Assignment:

    • int x = 10;
    • string name = "John";
  2. Expression Statements:

    • x = x + 5;
    • Console.WriteLine("Hello, World!");
  3. Conditional Statements:

    • if (condition)
    • if (condition) { ... }
    • else
    • else if (condition) { ... }
    • switch (variable) { ... }
  4. Loop Statements:

    • for (int i = 0; i < 10; i++) { ... }
    • while (condition) { ... }
    • do { ... } while (condition);
    • foreach (var item in collection) { ... }
  5. Jump Statements:

    • break;
    • continue;
    • return value;
    • goto label;
  6. Exception Handling:

    • try { ... }
    • catch (ExceptionType ex) { ... }
    • finally { ... }
    • throw new Exception("Error message");
  7. Method Calls:

    • Method();
    • int result = Add(5, 3);
  8. Object Creation and Initialization:

    • MyClass obj = new MyClass();
    • MyClass obj = new MyClass { Property1 = "Value1", Property2 = "Value2" };
  9. Lock Statement:

    • lock (lockObject) { ... }
  10. Checked and Unchecked Statements:

    • checked { ... }
    • unchecked { ... }
  11. Using Statement (for Resource Management):

    • using (var resource = new Resource()) { ... }
  12. Delegates and Events:

    • delegate void MyDelegate(int x);
    • event EventHandler MyEvent;
  13. Lambda Expressions:

    • (x, y) => x + y
    • (x) => { Console.WriteLine(x); }
  14. Attribute Usage:

    • [Attribute]
    • [Obsolete("This method is deprecated")]
  15. Unsafe Code (for Pointer Operations):

    • unsafe { ... }
  16. Asynchronous Programming (async/await):

    • async Task MyMethod() { ... }
    • await SomeAsyncOperation();
  17. Yield Statement (for Iterator Methods):

    • yield return item;
  18. Pattern Matching (C# 7.0+):

    • if (obj is int number) { ... }
  19. Local Functions (C# 7.0+):

    • int Add(int a, int b) { return a + b; }
  20. Record Types (C# 9.0+):

    • record Person(string FirstName, string LastName);
  21. Nullable Types:

    • int? nullableInt = null;
  22. Switch Expressions (C# 8.0+):

    • var result = variable switch { ... };
  23. Interpolated Strings (C# 6.0+):

    • string message = $"Hello, {name}!";
  24. Range and Index Operators (C# 8.0+):

    • var subArray = myArray[1..4];
  25. Pattern-Based Switch Statements (C# 9.0+):

    • int result = variable switch { ... };
  26. Discard (_) (C# 7.0+):

    • _ = SomeMethod();

Certainly! Here's the provided content with empty checkboxes:

Valid C# Patterns

Constant Patterns

  • 3: Matches the constant value 3.
  • "Hello": Matches the constant string "Hello".

Type Patterns

  • int x: Matches an integer and assigns it to variable x.
  • string s: Matches a string and assigns it to variable s.
  • var obj: Matches any type and assigns it to variable obj.

Var Pattern

  • var x: Matches any value and assigns it to variable x.

Wildcard Pattern

  • _: Matches any value but discards it.

Null Pattern (C# 8.0+)

  • null: Matches a null reference.

Property Pattern (C# 8.0+)

  • Person { Age: 18 }: Matches a Person object with an Age property set to 18.

Tuple Pattern (C# 7.0+)

  • (int x, int y): Matches a tuple with two integer values.
  • (string name, int age): Matches a tuple with a string name and an integer age.

Positional Pattern (C# 8.0+)

  • Point { X: 0, Y: 0 }: Matches a Point object with X and Y properties set to 0.
  • Rectangle { Width: var w, Height: var h }: Matches a Rectangle object and assigns Width and Height to w and h.

Recursive Pattern (C# 8.0+)

  • int[] { 1, 2, int rest }: Matches an array starting with elements 1 and 2, and assigns the rest to rest.
  • (1, 2, var rest): Matches a tuple starting with elements 1 and 2, and assigns the rest to rest.

Logical Patterns (C# 9.0+)

  • and pattern: and combines patterns.
    • int x and > 10: Matches an integer greater than 10.
  • or pattern: or combines patterns.
    • int x or string s: Matches an integer or a string.

Type Patterns with When Clause (C# 7.0+)

  • int x when x > 10: Matches an integer greater than 10 and assigns it to x.
  • string s when s.Length > 5: Matches a string with a length greater than 5 and assigns it to s.

Var Pattern with When Clause (C# 7.0+)

  • var x when x is int: Matches any value of type int and assigns it to x.

Binary Patterns (C# 9.0+)

  • a is b: Checks if a is of type b.
  • a as b: Attempts to cast a to type b and returns null if it fails.

Parenthesized Patterns (C# 8.0+)

  • (pattern): Groups patterns for precedence.

Relational Patterns (C# 9.0+)

  • a < b: Matches if a is less than b.
  • a <= b: Matches if a is less than or equal to b.
  • a > b: Matches if a is greater than b.
  • a >= b: Matches if a is greater than or equal to b.
  • a == b: Matches if a is equal to b.
  • a != b: Matches if a is not equal to b.

Valid C# Expressions

Primary Expressions

  • x: Identifier (variable or constant).
  • 123: Literal integer.
  • "Hello": Literal string.
  • true and false: Literal boolean values.
  • null: Null literal.
  • this: Current instance reference.
  • base: Base class reference.

Member Access Expressions

  • object.Member: Accessing a member (field, property, method, event, or nested type).
  • person.Name: Example property access.

Invocation Expressions

  • MethodName(): Method invocation with no arguments.
  • MethodName(arg1, arg2): Method invocation with arguments.
  • Math.Max(x, y): Example method call.

Element Access Expressions

  • array[index]: Accessing an array element.
  • dictionary[key]: Accessing a dictionary value.
  • list[0]: Example element access.

Object Creation Expressions

  • new ClassName(): Creating an instance of a class.
  • new List<int>(): Example object creation.
  • new { Name = "John", Age = 30 }: Creating an anonymous type.

Lambda Expressions

  • (x, y) => x + y: Lambda expression.
  • (int x) => { Console.WriteLine(x); }: Example lambda expression.

Anonymous Types (C# 3.0+)

  • new { Name = "John", Age = 30 }: Creating an anonymous type.
  • var person = new { Name = "Alice", Age = 25 }: Example anonymous type creation.

Object Initialization Expressions

  • new Person { Name = "Alice", Age = 25 }: Initializing an object.
  • new Point { X = 10, Y = 20 }: Example object initialization.

Collection Initialization Expressions (C# 3.0+)

  • new List<int> { 1, 2, 3 }: Initializing a collection.
  • var numbers = new List<int> { 1, 2, 3 }: Example collection initialization.

Array Initialization Expressions

  • new int[] { 1, 2, 3 }: Initializing an array.
  • int[] arr = { 1, 2, 3 }: Example array initialization.

Nullable Value Types

  • int? nullableInt = null;: Nullable integer.

Type Conversion Expressions

  • (int)x: Explicit type conversion.
  • x as T: Attempted type conversion (returns null if unsuccessful).
  • (T)x: Example explicit type conversion.

Arithmetic Expressions

  • x + y: Addition.
  • x - y: Subtraction.
  • x * y: Multiplication.
  • x / y: Division.
  • x % y: Modulus (remainder).

Relational Expressions

  • x < y: Less than.
  • x <= y: Less than or equal to.
  • x > y: Greater than.
  • x >= y: Greater than or equal to.
  • x == y: Equal to.
  • x != y: Not equal to.

Logical Expressions

  • x && y: Logical AND.
  • x || y: Logical OR.
  • !x: Logical NOT.

Conditional Expressions

  • condition ? trueExpression : falseExpression: Conditional (ternary) operator.
  • (x > 0) ? "Positive" : "Non-positive": Example usage of the conditional operator.

Assignment Expressions

  • x = y: Assignment.
  • x += y: Addition assignment.
  • x -= y: Subtraction assignment.
  • x *= y: Multiplication assignment.
  • x /= y: Division assignment.
  • x %= y: Modulus assignment.

Increment and Decrement Expressions

  • x++: Post-increment.
  • x--: Post-decrement.
  • ++x: Pre-increment.
  • --x: Pre-decrement.

Common BigInteger Methods and Properties

Constructors

  • BigInteger(): Initializes a new instance of the BigInteger class with a value of zero.
  • BigInteger(int value): Initializes a new instance of the BigInteger class with the specified integer value.
  • BigInteger(long value): Initializes a new instance of the BigInteger class with the specified long integer value.
  • BigInteger(byte[] bytes): Initializes a new instance of the BigInteger class from an array of bytes.

Static Methods

  • BigInteger.Add(BigInteger left, BigInteger right): Returns the result of adding two BigInteger values.
  • BigInteger.Subtract(BigInteger left, BigInteger right): Returns the result of subtracting one BigInteger value from another.
  • BigInteger.Multiply(BigInteger left, BigInteger right): Returns the result of multiplying two BigInteger values.
  • BigInteger.Divide(BigInteger dividend, BigInteger divisor): Returns the result of dividing one BigInteger value by another.
  • BigInteger.Remainder(BigInteger dividend, BigInteger divisor): Returns the remainder of dividing one BigInteger value by another.
  • BigInteger.Pow(BigInteger value, int exponent): Returns a BigInteger raised to a specified power.
  • BigInteger.Abs(BigInteger value): Returns the absolute value of a BigInteger value.
  • BigInteger.GreatestCommonDivisor(BigInteger left, BigInteger right): Returns the greatest common divisor of two BigInteger values.
  • BigInteger.Min(BigInteger left, BigInteger right): Returns the smaller of two BigInteger values.
  • BigInteger.Max(BigInteger left, BigInteger right): Returns the larger of two BigInteger values.

Properties

  • BitLength: Gets the number of bits in the two's complement representation of the BigInteger.
  • IsEven: Returns true if the BigInteger is an even number.
  • IsOne: Returns true if the BigInteger is equal to 1.
  • IsZero: Returns true if the BigInteger is equal to 0.
  • Sign: Gets a value indicating the sign of the BigInteger (-1 for negative, 0 for zero, 1 for positive).

Conversion Methods

  • ToByteArray(): Returns the BigInteger as a byte array.
  • ToDouble(): Converts the BigInteger to a double-precision floating-point number.
  • ToInt32(): Converts the BigInteger to a 32-bit signed integer.
  • ToInt64(): Converts the BigInteger to a 64-bit signed integer.
  • ToString(): Converts the BigInteger to its decimal string representation.
@Jim8y
Copy link
Contributor Author

Jim8y commented Jun 25, 2024

Need an update to C# 12 features.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant