C# Language Specification Support
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)
- [x] void: Represents the absence of a value or a method that does not return a value.
- [x] bool: Declares a variable of Boolean data type. Example:
bool isReady = true; - [x] byte: Declares a variable of 8-bit unsigned integer data type. Example:
byte myByte = 100; - [x] 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; - [x] int: Declares a variable of 32-bit signed integer data type. Example:
int count = 10; - [x] long: Declares a variable of 64-bit signed integer data type. Example:
long bigNumber = 1234567890L; - [x] sbyte: Declares a variable of 8-bit signed integer data type. Example:
sbyte smallNumber = -128; - [x] short: Declares a variable of 16-bit signed integer data type. Example:
short smallValue = 32767; - [x] uint: Declares a variable of 32-bit unsigned integer data type. Example:
uint positiveValue = 123; - [x] ulong: Declares a variable of 64-bit unsigned integer data type. Example:
ulong bigPositiveValue = 1234567890UL; - [x] ushort: Declares a variable of 16-bit unsigned integer data type. Example:
ushort smallPositiveValue = 65535; - [x] string: Declares a variable of string data type. Example:
string text = "Hello, world!"; - [x] object: Declares a variable of object data type. Example:
object myObject = new MyType(); - [x] System.Numerics.BigInteger: Represents a large integer data type. Example:
System.Numerics.BigInteger bigInt = 1234567890123456789012345678901234567890; - [x] List: Represents a list data type. Example:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; - [x] Map: Represents a map data type. Example:
Dictionary<string, int> keyValuePairs = new Dictionary<string, int>(); - [x] Neo.UInt160: Represents a 160-bit unsigned integer data type. Example:
Neo.UInt160 hash160Value = new Neo.UInt160(); - [x] 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
- [x] class: Declares a class. Example:
class MyClass { } - [x] struct: Declares a value type. Example:
struct Point { public int X; public int Y; } - [x] enum: Declares an enumeration. Example:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; - [x] delegate: Declares a delegate. Example:
delegate int MyDelegate(int x, int y); - [x] 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)
- [x] if: Starts an if statement. Example:
if (condition) { /* code */ } - [x] else: Defines an alternative branch in an if statement. Example:
if (condition) { /* true branch */ } else { /* else branch */ } - [x] switch: Starts a switch statement. Example:
switch (dayOfWeek) { case DayOfWeek.Monday: /* code */ break; } - [x] case: Defines individual cases in a switch statement. Example:
switch (dayOfWeek) { case DayOfWeek.Monday: Console.WriteLine("It's Monday."); break; } - [x] default: Specifies the default case in a switch statement. Example:
switch (dayOfWeek) { default: Console.WriteLine("It's another day."); break; } - [x] for: Starts a for loop. Example:
for (int i = 0; i < 10; i++) { /* loop body */ } - [x] foreach: Iterates over elements in a collection. Example:
foreach (var item in myList) { /* process item */ } - [x] while: Starts a while loop. Example:
while (condition) { /* loop body */ } - [x] do: Starts a do-while loop. Example:
do { /* loop body */ } while (condition); - [x] break: Exits a loop or switch statement prematurely. Example:
for (int i = 0; i < 10; i++) { if (i == 5) break; } - [x] continue: Jumps to the next iteration of a loop. Example:
for (int i = 0; i < 10; i++) { if (i == 5) continue; } - [x] goto: Transfers control to a labeled statement. Example: `goto MyLabel
- [x] return: Returns a value from a method. Example:
public int MyMethod() { return 42; } - [x] throw: Throws an exception. Example:
throw new Exception("An error occurred."); - [x] try: Starts a try-catch block. Example:
try { /* code */ } catch (Exception ex) { /* handle exception */ } - [x] catch: Catches and handles exceptions in a try-catch block. Example:
try { /* code that may throw an exception */ } catch (Exception ex) { /* handle exception */ } - [x] 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
- [x] public: Specifies access for a class or member to any code. Example:
public class MyClass { } - [x] private: Restricts access to a class or member. Example:
private int myField; - [x] 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 { } - [x] static: Declares a static member. Example:
public static void MyMethod() { /* code */ } - [x] readonly: Declares a read-only field. Example:
public readonly int MaxValue = 100; - [x] 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; - [x] abstract: Used to declare abstract classes or methods. Example:
abstract class Shape { } - [x] sealed: Prevents a class from being inherited. Example:
sealed class MySealedClass { } - [x] override: Overrides a base class member in a derived class. Example:
public override void MyMethod() { /* code */ } - [x] 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
- [x] as: Used for type casting or conversion. Example:
object obj = "Hello"; string str = obj as string; - [x] 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); - [x] checked: Enables overflow checking for arithmetic operations. Example:
checked { int result = int.MaxValue + 1; } - [x] 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 */ } - [x] params: Specifies a variable-length parameter list. Example:
public void MyMethod(params int[] numbers) { /* code */ } - [x] 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(); - [x] 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 */ } - [x] 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 */ } - [x] in: Specifies the iteration variable in a foreach loop. Example:
foreach (var item in myCollection) { /* code */ } - [x] null: Represents a null value. Example:
object obj = null; - [x] true: Represents the Boolean true value. Example:
bool isTrue = true; - [x] false: Represents the Boolean false value. Example:
bool isTrue = false; - [ ] stackalloc: Allocates memory on the stack. Example:
int* stackArray = stackalloc int[100]; - [x] 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
joinclause 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 byclause 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
letclause 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
joinclause 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 }; -
[x] 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
catchclause 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
- [x]
+: Adds two operands. Example:int result = 5 + 3; // result is 8 - [x]
-: Represents subtraction when used between two numeric values, such asx - y. Example:int result = 10 - 5; // result is 5 - [x]
-: 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 - [x]
*: Multiplies two operands. Example:int result = 7 * 2; // result is 14 - [x]
/: Divides the first operand by the second. Example:int result = 16 / 4; // result is 4 - [x]
%: Returns the remainder of the division. Example:int result = 17 % 5; // result is 2
Comparison Operators
- [x]
==: Checks if two values are equal. Example:bool isEqual = (x == y); - [x]
!=: Checks if two values are not equal. Example:bool isNotEqual = (x != y); - [x]
<: Checks if the first value is less than the second. Example:bool isLess = (x < y); - [x]
>: Checks if the first value is greater than the second. Example:bool isGreater = (x > y); - [x]
<=: Checks if the first value is less than or equal to the second. Example:bool isLessOrEqual = (x <= y); - [x]
>=: Checks if the first value is greater than or equal to the second. Example:bool isGreaterOrEqual = (x >= y);
Logical Operators
- [x]
&&: Logical AND operator. Returns true if both operands are true. Example:bool result = (x && y); - [x]
||: Logical OR operator. Returns true if at least one operand is true. Example:bool result = (x || y); - [x]
!: Logical NOT operator. Inverts the value of the operand. Example:bool result = !x;
Bitwise Operators
- [x]
&: Bitwise AND operator. Performs a bitwise AND operation between two integers. Example:int result = x & y; - [x]
|: Bitwise OR operator. Performs a bitwise OR operation between two integers. Example:int result = x | y; - [x]
^: Bitwise XOR operator. Performs a bitwise XOR operation between two integers. Example:int result = x ^ y; - [x]
~: Bitwise NOT operator. Inverts the bits of an integer. Example:int result = ~x; - [x]
<<: Left shift operator. Shifts the bits of an integer to the left. Example:int result = x << 2; - [x]
>>: Right shift operator. Shifts the bits of an integer to the right. Example:int result = x >> 2;
Assignment Operators
- [x]
=: Assigns the value of the right operand to the left operand. Example:x = 10; - [x]
+=: Adds the right operand to the left operand and assigns the result. Example:x += 5; - [x]
-=: Subtracts the right operand from the left operand and assigns the result. Example:x -= 3; - [x]
*=: Multiplies the left operand by the right operand and assigns the result. Example:x *= 2; - [x]
/=: Divides the left operand by the right operand and assigns the result. Example:x /= 4; - [x]
%=: Calculates the remainder of the left operand divided by the right operand and assigns the result. Example:x %= 3; - [x]
&=: Performs a bitwise AND operation between the left and right operands and assigns the result. Example:x &= y; - [x]
|=: Performs a bitwise OR operation between the left and right operands and assigns the result. Example:x |= y; - [x]
^=: Performs a bitwise XOR operation between the left and right operands and assigns the result. Example:x ^= y; - [x]
<<=: 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; - [x]
>>=: 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; - [x]
??=: Assigns the value of the right operand to the left operand only if the left operand isnull. Example:x ??= defaultValue;
Other Operators
- [x]
??: 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 - [x]
++: Increment operator. Increases the value of a variable by 1. Example:x++; - [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
- [x]
int: Represents a 32-bit signed integer. Example:int number = 42; - [x]
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; - [x]
char: Represents a Unicode character. Example:char letter = 'A'; - [x]
bool: Represents a Boolean value (true or false). Example:bool isTrue = true; - [x]
byte: Represents an 8-bit unsigned integer. Example:byte smallNumber = 100; - [x]
sbyte: Represents an 8-bit signed integer. Example:sbyte smallNumber = -128; - [x]
short: Represents a 16-bit signed integer. Example:short smallValue = 32767; - [x]
ushort: Represents a 16-bit unsigned integer. Example:ushort smallPositiveValue = 65535; - [x]
uint: Represents a 32-bit unsigned integer. Example:uint positiveValue = 123; - [x]
ulong: Represents a 64-bit unsigned integer. Example:ulong bigPositiveValue = 1234567890UL; - [x]
enum: Represents an enumeration. Example:enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; - [x]
struct: Represents a value type. Example:struct Point { public int X; public int Y; }
Reference Types
- [x]
string: Represents a sequence of characters. Example:string text = "Hello, world!"; - [x]
object: Represents a base type for all types in C#. Example:object obj = new MyType(); - [x]
class: Represents a reference type (class definition). Example:class MyClass { } - [ ]
interface: Represents an interface. Example:interface IMyInterface { /* interface members */ } - [x]
delegate: Represents a delegate. Example:delegate int MyDelegate(int x, int y); - [ ]
dynamic: Represents a dynamically-typed object. Example:dynamic dynVar = 42; - [x]
array: Represents an array. Example:int[] numbers = { 1, 2, 3, 4, 5 };
4. Syntactic Sugar and Advanced Features
- [x] Auto Properties: Used to simplify property declaration with getter and setter methods. Example:
public int MyProperty { get; set; } - [x] Object and Collection Initializers: Allow concise initialization of objects and collections. Example:
var person = new Person { FirstName = "John", LastName = "Doe", Age = 30 }; - [x] 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 } - [x] Pattern Matching: Simplify conditional code with pattern-based matching. Example:
if (obj is string text) { // code using 'text' as a string } - [x] 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; } - [x] Delegates and Events: Enable the creation of delegate types and event handlers. Example:
public delegate void MyDelegate(string message); public event MyDelegate MyEvent; - [x] 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"); - [x] 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#ifconditions. - [ ]
#elif: Specifies additional conditions for#ifblocks. - [ ]
#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:
- [ ]
inttolong - [ ]
inttodouble - [ ]
floattodouble - [ ]
shorttoint - [ ]
bytetoint - [ ]
decimaltodouble - [ ]
chartointString Conversions: - [ ]
stringtoint - [ ]
stringtodouble - [ ]
stringtoDateTime - [ ]
stringtoboolBoolean Conversions: - [ ]
booltoint(1 fortrue, 0 forfalse) - [ ]
booltostringEnum Conversions: - [ ] Enum to its underlying numeric type (e.g.,
enumtoint) - [ ] Numeric type to an enum (e.g.,
inttoenum) Nullable Types: - [ ] Converting between nullable and non-nullable versions of value types (e.g.,
int?toint) - [ ] Converting between nullable types (e.g.,
int?todouble?) Array Conversions: - [ ] Converting between arrays of different types (e.g.,
int[]todouble[]) Object Conversions: - [ ] Converting between an object and a specific type (e.g.,
objecttostring) 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
DateTimetostring(and vice versa) in various formats - [ ] Extracting date or time components from
DateTimeobjects 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 numbersxandy. - [ ]
Math.Subtract(x, y): Subtractsyfromx. - [ ]
Math.Multiply(x, y): Multiplies two numbersxandy. - [ ]
Math.Divide(x, y): Dividesxbyy.
Exponentiation and Logarithms:
- [ ]
Math.Pow(x, y): Returnsxraised to the power ofy. - [ ]
Math.Sqrt(x): Calculates the square root ofx. - [ ]
Math.Log(x): Returns the natural logarithm ofx. - [ ]
Math.Log10(x): Returns the base 10 logarithm ofx.
Trigonometric Functions:
- [ ]
Math.Sin(x): Returns the sine of the anglexin radians. - [ ]
Math.Cos(x): Returns the cosine of the anglexin radians. - [ ]
Math.Tan(x): Returns the tangent of the anglexin 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 ofyandx.
Rounding and Precision:
- [ ]
Math.Round(x): Rounds a numberxto the nearest integer. - [ ]
Math.Floor(x): Roundsxdown to the nearest integer. - [ ]
Math.Ceiling(x): Roundsxup to the nearest integer. - [ ]
Math.Truncate(x): Truncatesxto an integer by removing its fractional part. - [ ]
Math.Round(x, decimals): Roundsxto a specified number of decimal places.
Absolute and Sign:
- [x]
Math.Abs(x): Returns the absolute (non-negative) value ofx. - [x]
Math.Sign(x): Returns the sign ofx(-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 betweenmin(inclusive) andmax(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:
- [x]
Math.Max(x, y): Returns the larger of two numbersxandy. - [x]
Math.Min(x, y): Returns the smaller of two numbersxandy. - [ ]
Math.Clamp(x, min, max): Limits the value ofxto be within the range[min, max].
Common String Methods in C#
-
String Length:
- [x]
string.Length: Returns the length (number of characters) of a string.
- [x]
-
Substring Extraction:
- [x]
string.Substring(startIndex): Returns a substring starting from the specifiedstartIndexto the end of the string. - [x]
string.Substring(startIndex, length): Returns a substring starting from the specifiedstartIndexwith the specifiedlength.
- [x]
-
Concatenation:
- [ ]
string.Concat(str1, str2, ...): Concatenates multiple strings together.
- [ ]
-
String Interpolation:
- [ ]
$"...": Allows you to embed expressions and variables directly within a string.
- [ ]
-
String Formatting:
- [ ]
string.Format(format, arg0, arg1, ...): Formats a string with placeholders and values.
- [ ]
-
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.
- [ ]
-
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.
- [ ]
-
String Manipulation:
- [ ]
string.ToUpper(): Converts the string to uppercase. - [ ]
string.ToLower(): Converts the string to lowercase. - [ ]
string.Trim(): Removes leading and trailing whitespace.
- [ ]
-
String Splitting:
- [ ]
string.Split(delimiters): Splits a string into an array of substrings based on specified delimiters.
- [ ]
-
String Replacement:
- [ ]
string.Replace(oldValue, newValue): Replaces all occurrences ofoldValuewithnewValue.
- [ ]
-
String Empty or Null Check:
- [ ]
string.IsNullOrEmpty(str): Checks if a string is eithernullor empty. - [ ]
string.IsNullOrWhiteSpace(str): Checks if a string isnull, 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
-
[ ]
Where: Filters a sequence of elements based on a given condition.- Example:
var result = numbers.Where(x => x > 5);
- Example:
-
[ ]
Select: Transforms each element of a sequence into a new form.- Example:
var result = names.Select(name => name.ToUpper());
- Example:
-
[ ]
OrderByandOrderByDescending: Sorts elements in ascending or descending order based on a specified key.- Example:
var result = numbers.OrderBy(x => x);
- Example:
-
[ ]
GroupBy: Groups elements based on a key and returns groups of elements.- Example:
var result = products.GroupBy(product => product.Category);
- Example:
-
[ ]
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 });
- Example:
-
[ ]
AnyandAll: Checks if any or all elements in a sequence satisfy a condition.- Example:
bool anyPositive = numbers.Any(x => x > 0);
- Example:
-
[ ]
First,FirstOrDefault,Last, andLastOrDefault: Retrieves the first or last element in a sequence, optionally with a condition.- Example:
var firstPositive = numbers.First(x => x > 0);
- Example:
-
[ ]
Single,SingleOrDefault: Retrieves the single element in a sequence that satisfies a condition.- Example:
var singlePositive = numbers.Single(x => x > 0);
- Example:
Set Operations
-
[ ]
Union: Combines two sequences, removing duplicates.- Example:
var result = sequence1.Union(sequence2);
- Example:
-
[ ]
Intersect: Returns the common elements between two sequences.- Example:
var result = sequence1.Intersect(sequence2);
- Example:
-
[ ]
Except: Returns elements that are present in one sequence but not in another.- Example:
var result = sequence1.Except(sequence2);
- Example:
Aggregation
-
[ ]
Count: Returns the number of elements in a sequence.- Example:
int count = numbers.Count();
- Example:
-
[ ]
Sum,Min, andMax: Calculates the sum, minimum, or maximum value in a sequence.- Example:
int sum = numbers.Sum();
- Example:
-
[ ]
Average: Computes the average value of elements in a sequence.- Example:
double average = numbers.Average();
- Example:
-
[ ]
Aggregate: Performs a custom aggregation operation on elements in a sequence.- Example:
var result = numbers.Aggregate((x, y) => x * y);
- Example:
Conversion
-
[ ]
ToListandToArray: Converts a sequence to a list or an array.- Example:
List<int> list = numbers.ToList();
- Example:
-
[ ]
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);
- Example:
-
[ ]
OfType: Filters elements of a sequence to include only those of a specific type.- Example:
var result = mixedObjects.OfType<string>();
- Example:
-
[ ]
Cast: Casts elements of a sequence to a specified type.- Example:
var result = mixedObjects.Cast<int>();
- Example:
Valid C# Statements
-
[x] Variable Declaration and Assignment:
-
int x = 10; -
string name = "John";
-
-
[x] Expression Statements:
-
x = x + 5; -
Console.WriteLine("Hello, World!");
-
-
[x] Conditional Statements:
-
if (condition) -
if (condition) { ... } -
else -
else if (condition) { ... } -
switch (variable) { ... }
-
-
[x] Loop Statements:
-
for (int i = 0; i < 10; i++) { ... } -
while (condition) { ... } -
do { ... } while (condition); -
foreach (var item in collection) { ... }
-
-
[x] Jump Statements:
-
break; -
continue; -
return value; -
goto label;
-
-
[x] Exception Handling:
-
try { ... } -
catch (ExceptionType ex) { ... } -
finally { ... } -
throw new Exception("Error message");
-
-
[x] Method Calls:
-
Method(); -
int result = Add(5, 3);
-
-
[x] Object Creation and Initialization:
-
MyClass obj = new MyClass(); -
MyClass obj = new MyClass { Property1 = "Value1", Property2 = "Value2" };
-
-
[ ] Lock Statement:
-
lock (lockObject) { ... }
-
-
[x] Checked and Unchecked Statements:
-
checked { ... } -
unchecked { ... }
-
-
[ ] Using Statement (for Resource Management):
-
using (var resource = new Resource()) { ... }
-
-
[x] Delegates and Events:
-
delegate void MyDelegate(int x); -
event EventHandler MyEvent;
-
-
[ ] Lambda Expressions:
-
(x, y) => x + y -
(x) => { Console.WriteLine(x); }
-
-
[ ] Attribute Usage:
-
[Attribute] -
[Obsolete("This method is deprecated")]
-
-
[ ] Unsafe Code (for Pointer Operations):
-
unsafe { ... }
-
-
[ ] Asynchronous Programming (async/await):
-
async Task MyMethod() { ... } -
await SomeAsyncOperation();
-
-
[ ] Yield Statement (for Iterator Methods):
-
yield return item;
-
-
[ ] Pattern Matching (C# 7.0+):
-
if (obj is int number) { ... }
-
-
[ ] Local Functions (C# 7.0+):
-
int Add(int a, int b) { return a + b; }
-
-
[ ] Record Types (C# 9.0+):
-
record Person(string FirstName, string LastName);
-
-
[x] Nullable Types:
-
int? nullableInt = null;
-
-
[x] Switch Expressions (C# 8.0+):
-
var result = variable switch { ... };
-
-
[x] Interpolated Strings (C# 6.0+):
-
string message = $"Hello, {name}!";
-
-
[x] Range and Index Operators (C# 8.0+):
-
var subArray = myArray[1..4];
-
-
[x] Pattern-Based Switch Statements (C# 9.0+):
-
int result = variable switch { ... };
-
-
[x] Discard (_) (C# 7.0+):
-
_ = SomeMethod();
-
Certainly! Here's the provided content with empty checkboxes:
Valid C# Patterns
Constant Patterns
- [x]
3: Matches the constant value 3. - [x]
"Hello": Matches the constant string "Hello".
Type Patterns
- [x]
int x: Matches an integer and assigns it to variablex. - [x]
string s: Matches a string and assigns it to variables. - [x]
var obj: Matches any type and assigns it to variableobj.
Var Pattern
- [x]
var x: Matches any value and assigns it to variablex.
Wildcard Pattern
- [x]
_: Matches any value but discards it.
Null Pattern (C# 8.0+)
- [x]
null: Matches anullreference.
Property Pattern (C# 8.0+)
- [x]
Person { Age: 18 }: Matches aPersonobject with anAgeproperty set to 18.
Tuple Pattern (C# 7.0+)
- [x]
(int x, int y): Matches a tuple with two integer values. - [x]
(string name, int age): Matches a tuple with a stringnameand an integerage.
Positional Pattern (C# 8.0+)
- [x]
Point { X: 0, Y: 0 }: Matches aPointobject withXandYproperties set to 0. - [x]
Rectangle { Width: var w, Height: var h }: Matches aRectangleobject and assignsWidthandHeighttowandh.
Recursive Pattern (C# 8.0+)
- [ ]
int[] { 1, 2, int rest }: Matches an array starting with elements 1 and 2, and assigns the rest torest. - [ ]
(1, 2, var rest): Matches a tuple starting with elements 1 and 2, and assigns the rest torest.
Logical Patterns (C# 9.0+)
- [ ]
andpattern:andcombines patterns.- [ ]
int x and > 10: Matches an integer greater than 10.
- [ ]
- [ ]
orpattern:orcombines patterns.- [ ]
int x or string s: Matches an integer or a string.
- [ ]
Type Patterns with When Clause (C# 7.0+)
- [x]
int x when x > 10: Matches an integer greater than 10 and assigns it tox. - [x]
string s when s.Length > 5: Matches a string with a length greater than 5 and assigns it tos.
Var Pattern with When Clause (C# 7.0+)
- [ ]
var x when x is int: Matches any value of typeintand assigns it tox.
Binary Patterns (C# 9.0+)
- [x]
a is b: Checks ifais of typeb. - [x]
a as b: Attempts to castato typeband returnsnullif it fails.
Parenthesized Patterns (C# 8.0+)
- [x]
(pattern): Groups patterns for precedence.
Relational Patterns (C# 9.0+)
- [x]
a < b: Matches ifais less thanb. - [x]
a <= b: Matches ifais less than or equal tob. - [x]
a > b: Matches ifais greater thanb. - [x]
a >= b: Matches ifais greater than or equal tob. - [x]
a == b: Matches ifais equal tob. - [x]
a != b: Matches ifais not equal tob.
Valid C# Expressions
Primary Expressions
- [x]
x: Identifier (variable or constant). - [x]
123: Literal integer. - [x]
"Hello": Literal string. - [x]
trueandfalse: Literal boolean values. - [x]
null: Null literal. - [x]
this: Current instance reference. - [ ]
base: Base class reference.
Member Access Expressions
- [x]
object.Member: Accessing a member (field, property, method, event, or nested type). -
person.Name: Example property access.
Invocation Expressions
- [x]
MethodName(): Method invocation with no arguments. - [x]
MethodName(arg1, arg2): Method invocation with arguments. -
Math.Max(x, y): Example method call.
Element Access Expressions
- [x]
array[index]: Accessing an array element. - [x]
dictionary[key]: Accessing a dictionary value. -
list[0]: Example element access.
Object Creation Expressions
- [x]
new ClassName(): Creating an instance of a class. - [x]
new List<int>(): Example object creation. - [x]
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+)
- [x]
new { Name = "John", Age = 30 }: Creating an anonymous type. -
var person = new { Name = "Alice", Age = 25 }: Example anonymous type creation.
Object Initialization Expressions
- [x]
new Person { Name = "Alice", Age = 25 }: Initializing an object. -
new Point { X = 10, Y = 20 }: Example object initialization.
Collection Initialization Expressions (C# 3.0+)
- [x]
new List<int> { 1, 2, 3 }: Initializing a collection. -
var numbers = new List<int> { 1, 2, 3 }: Example collection initialization.
Array Initialization Expressions
- [x]
new int[] { 1, 2, 3 }: Initializing an array. -
int[] arr = { 1, 2, 3 }: Example array initialization.
Nullable Value Types
- [x]
int? nullableInt = null;: Nullable integer.
Type Conversion Expressions
- [x]
(int)x: Explicit type conversion. - [ ]
x as T: Attempted type conversion (returnsnullif unsuccessful). -
(T)x: Example explicit type conversion.
Arithmetic Expressions
- [x]
x + y: Addition. - [x]
x - y: Subtraction. - [x]
x * y: Multiplication. - [x]
x / y: Division. - [x]
x % y: Modulus (remainder).
Relational Expressions
- [x]
x < y: Less than. - [x]
x <= y: Less than or equal to. - [x]
x > y: Greater than. - [x]
x >= y: Greater than or equal to. - [x]
x == y: Equal to. - [x]
x != y: Not equal to.
Logical Expressions
- [x]
x && y: Logical AND. - [x]
x || y: Logical OR. - [x]
!x: Logical NOT.
Conditional Expressions
- [x]
condition ? trueExpression : falseExpression: Conditional (ternary) operator. -
(x > 0) ? "Positive" : "Non-positive": Example usage of the conditional operator.
Assignment Expressions
- [x]
x = y: Assignment. - [x]
x += y: Addition assignment. - [x]
x -= y: Subtraction assignment. - [x]
x *= y: Multiplication assignment. - [x]
x /= y: Division assignment. - [x]
x %= y: Modulus assignment.
Increment and Decrement Expressions
- [x]
x++: Post-increment. - [x]
x--: Post-decrement. - [x]
++x: Pre-increment. - [x]
--x: Pre-decrement.
Common BigInteger Methods and Properties
Constructors
- [ ]
BigInteger(): Initializes a new instance of theBigIntegerclass with a value of zero. - [x]
BigInteger(int value): Initializes a new instance of theBigIntegerclass with the specified integer value. - [x]
BigInteger(long value): Initializes a new instance of theBigIntegerclass with the specified long integer value. - [ ]
BigInteger(byte[] bytes): Initializes a new instance of theBigIntegerclass from an array of bytes.
Static Methods
- [ ]
BigInteger.Add(BigInteger left, BigInteger right): Returns the result of adding twoBigIntegervalues. - [ ]
BigInteger.Subtract(BigInteger left, BigInteger right): Returns the result of subtracting oneBigIntegervalue from another. - [ ]
BigInteger.Multiply(BigInteger left, BigInteger right): Returns the result of multiplying twoBigIntegervalues. - [ ]
BigInteger.Divide(BigInteger dividend, BigInteger divisor): Returns the result of dividing oneBigIntegervalue by another. - [ ]
BigInteger.Remainder(BigInteger dividend, BigInteger divisor): Returns the remainder of dividing oneBigIntegervalue by another. - [x]
BigInteger.Pow(BigInteger value, int exponent): Returns aBigIntegerraised to a specified power. - [ ]
BigInteger.Abs(BigInteger value): Returns the absolute value of aBigIntegervalue. - [ ]
BigInteger.GreatestCommonDivisor(BigInteger left, BigInteger right): Returns the greatest common divisor of twoBigIntegervalues. - [ ]
BigInteger.Min(BigInteger left, BigInteger right): Returns the smaller of twoBigIntegervalues. - [ ]
BigInteger.Max(BigInteger left, BigInteger right): Returns the larger of twoBigIntegervalues.
Properties
- [ ]
BitLength: Gets the number of bits in the two's complement representation of theBigInteger. - [ ]
IsEven: Returnstrueif theBigIntegeris an even number. - [x]
IsOne: Returnstrueif theBigIntegeris equal to 1. - [x]
IsZero: Returnstrueif theBigIntegeris equal to 0. - [x]
Sign: Gets a value indicating the sign of theBigInteger(-1 for negative, 0 for zero, 1 for positive).
Conversion Methods
- [x]
ToByteArray(): Returns theBigIntegeras a byte array. - [ ]
ToDouble(): Converts theBigIntegerto a double-precision floating-point number. - [ ]
ToInt32(): Converts theBigIntegerto a 32-bit signed integer. - [ ]
ToInt64(): Converts theBigIntegerto a 64-bit signed integer. - [ ]
ToString(): Converts theBigIntegerto its decimal string representation.
Need an update to C# 12 features.