You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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 */ }
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;
group: Used in a group by clause in LINQ queries. Example:
varquery=frompersoninpeople
group person by person.City into cityGroupselectnew{ City = cityGroup.Key, Count = cityGroup.Count()};
into: Used in LINQ queries to create a new range variable. Example:
varquery=frompersoninpeople
group person by person.City into cityGroupwhere cityGroup.Count()>2selectnew{ City = cityGroup.Key, Count = cityGroup.Count()};
join: Used in LINQ queries to perform a join operation. Example:
varquery=frompersoninpeople
join city in cities on person.CityId equals city.Id
selectnew{ person.Name, city.CityName };
let: Used in a let clause in LINQ queries to define a new variable. Example:
+: 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;
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:
varperson=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:
varresult=fromnuminnumberswherenum%2==0selectnum;
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 */ }
$"...": 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 of oldValue with newValue.
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
Where: Filters a sequence of elements based on a given condition.
Example: var result = numbers.Where(x => x > 5);
Select: Transforms each element of a sequence into a new form.
Example: var result = names.Select(name => name.ToUpper());
OrderBy and OrderByDescending: Sorts elements in ascending or descending order based on a specified key.
Example: var result = numbers.OrderBy(x => x);
GroupBy: Groups elements based on a key and returns groups of elements.
Example: var result = products.GroupBy(product => product.Category);
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 });
Any and All: Checks if any or all elements in a sequence satisfy a condition.
Example: bool anyPositive = numbers.Any(x => x > 0);
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);
Single, SingleOrDefault: Retrieves the single element in a sequence that satisfies a condition.
Example: var singlePositive = numbers.Single(x => x > 0);
Set Operations
Union: Combines two sequences, removing duplicates.
Example: var result = sequence1.Union(sequence2);
Intersect: Returns the common elements between two sequences.
Example: var result = sequence1.Intersect(sequence2);
Except: Returns elements that are present in one sequence but not in another.
Example: var result = sequence1.Except(sequence2);
Aggregation
Count: Returns the number of elements in a sequence.
Example: int count = numbers.Count();
Sum, Min, and Max: Calculates the sum, minimum, or maximum value in a sequence.
Example: int sum = numbers.Sum();
Average: Computes the average value of elements in a sequence.
Example: double average = numbers.Average();
Aggregate: Performs a custom aggregation operation on elements in a sequence.
Example: var result = numbers.Aggregate((x, y) => x * y);
Conversion
ToList and ToArray: Converts a sequence to a list or an array.
Example: List<int> list = numbers.ToList();
ToDictionary: Converts a sequence into a dictionary based on key and value selectors.
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)
bool isReady = true;
byte myByte = 100;
char myChar = 'A';
decimal price = 19.99M;
double pi = 3.14159265359;
float price = 19.99F;
int count = 10;
long bigNumber = 1234567890L;
sbyte smallNumber = -128;
short smallValue = 32767;
uint positiveValue = 123;
ulong bigPositiveValue = 1234567890UL;
ushort smallPositiveValue = 65535;
string text = "Hello, world!";
object myObject = new MyType();
System.Numerics.BigInteger bigInt = 1234567890123456789012345678901234567890;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();
Neo.UInt160 hash160Value = new Neo.UInt160();
Neo.UInt256 hash256Value = new Neo.UInt256();
C# to Neo smart contract type mapping table:
bool
Boolean
byte
Integer
sbyte
Integer
short
Integer
ushort
Integer
int
Integer
uint
Integer
long
Integer
ulong
Integer
char
Integer
string
ByteString
byte[]
ByteArray
BigInteger
Integer
Integer
Array
object
Any
void
Void
Neo.Cryptography.ECC.ECPoint
PublicKey
Neo.SmartContract.Framework.ByteString
ByteString
Neo.UInt160
Hash160
Neo.UInt256
Hash256
ByteArray
Classes and Structures
class MyClass { }
struct Point { public int X; public int Y; }
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
delegate int MyDelegate(int x, int y);
interface IMyInterface { /* interface members */ }
Control Flow Keywords (https://github.com/neo-project/neo-devpack-dotnet/blob/master/src/Neo.Compiler.CSharp/MethodConvert.cs)
if (condition) { /* code */ }
if (condition) { /* true branch */ } else { /* else branch */ }
switch (dayOfWeek) { case DayOfWeek.Monday: /* code */ break; }
switch (dayOfWeek) { case DayOfWeek.Monday: Console.WriteLine("It's Monday."); break; }
switch (dayOfWeek) { default: Console.WriteLine("It's another day."); break; }
for (int i = 0; i < 10; i++) { /* loop body */ }
foreach (var item in myList) { /* process item */ }
while (condition) { /* loop body */ }
do { /* loop body */ } while (condition);
for (int i = 0; i < 10; i++) { if (i == 5) break; }
for (int i = 0; i < 10; i++) { if (i == 5) continue; }
public int MyMethod() { return 42; }
throw new Exception("An error occurred.");
try { /* code */ } catch (Exception ex) { /* handle exception */ }
try { /* code that may throw an exception */ } catch (Exception ex) { /* handle exception */ }
try { /* code */ } catch (Exception ex) { /* handle exception */ } finally { /* cleanup code */ }
Access Modifiers and Member Control
public class MyClass { }
private int myField;
protected void MyMethod() { /* code */ }
internal class MyInternalClass { }
public static void MyMethod() { /* code */ }
public readonly int MaxValue = 100;
const int MaxValue = 100;
private volatile int counter;
abstract class Shape { }
sealed class MySealedClass { }
public override void MyMethod() { /* code */ }
public virtual void MyMethod() { /* code */ }
extern void NativeMethod();
Type Conversion and Checking
object obj = "Hello"; string str = obj as string;
if (myObject is MyClass) { /* code */ }
Type type = typeof(MyClass);
int size = sizeof(int);
checked { int result = int.MaxValue + 1; }
unchecked { int result = int.MaxValue + 1; }
public static implicit operator MyType(int value) { /* conversion logic */ }
public static explicit operator int(MyClass myObj) { /* conversion logic */ }
Parameters and Methods
public void MyMethod(ref int value) { /* code */ }
public void MyMethod(out int result) { /* code */ }
public void MyMethod(params int[] numbers) { /* code */ }
this.myField = 42;
base.MethodName();
new MyType();
Special Keywords
public static MyType operator +(MyType a, MyType b) { /* operator logic */ }
public event EventHandler MyEvent;
lock (myLockObject) { /* code */ }
fixed (int* ptr = &myVariable) { /* code */ }
unsafe { /* unsafe code */ }
foreach (var item in myCollection) { /* code */ }
object obj = null;
bool isTrue = true;
bool isTrue = false;
int* stackArray = stackalloc int[100];
using (var resource = new MyResource()) { /* code */ }
Contextual Keywords
add: Used in property declarations to add an event handler. Example:
alias: Used to provide a namespace or type alias. Example:
ascending: Used in LINQ queries to specify ascending sorting. Example:
async: Marks a method as asynchronous.
Example:
await: Suspends the execution of an asynchronous method until the awaited task completes. Example:
by: Used in a
join
clause in LINQ queries to specify the join condition. Example:descending: Used in LINQ queries to specify descending sorting. Example:
dynamic: Declares a dynamic type that bypasses compile-time type checking. Example:
equals: Used in pattern matching to check if a value matches a specified pattern. Example:
from: Used in LINQ queries to specify the data source. Example:
get: Defines a property's getter method. Example:
global: Used to reference items from the global namespace. Example:
group: Used in a
group by
clause in LINQ queries. Example:into: Used in LINQ queries to create a new range variable. Example:
join: Used in LINQ queries to perform a join operation. Example:
let: Used in a
let
clause in LINQ queries to define a new variable. Example:nameof: Returns the name of a variable, type, or member as a string. Example:
on: Used in a
join
clause in LINQ queries to specify the join condition. Example:orderby: Used in LINQ queries to specify sorting. Example:
partial: Indicates that a class, struct, or interface is defined in multiple files. Example:
remove: Used in property declarations to remove an event handler. Example:
select: Used in LINQ queries to specify the projection. Example:
set: Defines a property's setter method. Example:
unmanaged: Used to specify an unmanaged generic type constraint. Example:
value: Refers to the value of a property or indexer within a property or indexer accessor. Example:
var: Declares an implicitly typed local variable. Example:
when: Used in a
catch
clause to specify an exception filter. Example:where: Used in LINQ queries to specify filtering criteria. Example:
yield: Used to return values from an iterator method. Example:
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 asx - 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 isnull
. 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
public int MyProperty { get; set; }
string name = $"Hello, {firstName} {lastName}!";
var person = new { Name = "John", Age = 30 };
(x, y) => x + y
public static string Reverse(this string str) { /* code */ }
public class List<T> { /* code */ }
async
,await
): Facilitate non-blocking code execution. Example:(int, string) result = (42, "Hello");
string? nullableString = null;
var subArray = myArray[1..4];
5. Other Features
public int MyProperty { get; set; }
namespace MyNamespace { /* code */ }
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
tolong
int
todouble
float
todouble
short
toint
byte
toint
decimal
todouble
char
toint
String Conversions:
string
toint
string
todouble
string
toDateTime
string
tobool
Boolean Conversions:
bool
toint
(1 fortrue
, 0 forfalse
)bool
tostring
Enum Conversions:
enum
toint
)int
toenum
)Nullable Types:
int?
toint
)int?
todouble?
)Array Conversions:
int[]
todouble[]
)Object Conversions:
object
tostring
)Casting and Explicit Conversions:
(int)doubleValue
)DateTime Conversions:
DateTime
tostring
(and vice versa) in various formatsDateTime
objectsCustom Type Conversions (User-Defined):
Base Type Conversions:
Implicit and Explicit Interface Implementations:
Common Mathematical Methods and Functions in C#
Basic Arithmetic Operations:
Math.Add(x, y)
: Adds two numbersx
andy
.Math.Subtract(x, y)
: Subtractsy
fromx
.Math.Multiply(x, y)
: Multiplies two numbersx
andy
.Math.Divide(x, y)
: Dividesx
byy
.Exponentiation and Logarithms:
Math.Pow(x, y)
: Returnsx
raised 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 anglex
in radians.Math.Cos(x)
: Returns the cosine of the anglex
in radians.Math.Tan(x)
: Returns the tangent of the anglex
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 ofy
andx
.Rounding and Precision:
Math.Round(x)
: Rounds a numberx
to the nearest integer.Math.Floor(x)
: Roundsx
down to the nearest integer.Math.Ceiling(x)
: Roundsx
up to the nearest integer.Math.Truncate(x)
: Truncatesx
to an integer by removing its fractional part.Math.Round(x, decimals)
: Roundsx
to a specified number of decimal places.Absolute and Sign:
Math.Abs(x)
: Returns the absolute (non-negative) value ofx
.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:
Math.Max(x, y)
: Returns the larger of two numbersx
andy
.Math.Min(x, y)
: Returns the smaller of two numbersx
andy
.Math.Clamp(x, min, max)
: Limits the value ofx
to be within the range[min, max]
.Common String Methods in C#
string.Length
: Returns the length (number of characters) of a string.string.Substring(startIndex)
: Returns a substring starting from the specifiedstartIndex
to the end of the string.string.Substring(startIndex, length)
: Returns a substring starting from the specifiedstartIndex
with the specifiedlength
.string.Concat(str1, str2, ...)
: Concatenates multiple strings together.$"..."
: Allows you to embed expressions and variables directly within a string.string.Format(format, arg0, arg1, ...)
: Formats a string with placeholders and values.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.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.ToUpper()
: Converts the string to uppercase.string.ToLower()
: Converts the string to lowercase.string.Trim()
: Removes leading and trailing whitespace.string.Split(delimiters)
: Splits a string into an array of substrings based on specified delimiters.string.Replace(oldValue, newValue)
: Replaces all occurrences ofoldValue
withnewValue
.string.IsNullOrEmpty(str)
: Checks if a string is eithernull
or 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.var result = numbers.Where(x => x > 5);
Select
: Transforms each element of a sequence into a new form.var result = names.Select(name => name.ToUpper());
OrderBy
andOrderByDescending
: Sorts elements in ascending or descending order based on a specified key.var result = numbers.OrderBy(x => x);
GroupBy
: Groups elements based on a key and returns groups of elements.var result = products.GroupBy(product => product.Category);
Join
: Combines two collections based on a common key.var result = customers.Join(orders, customer => customer.Id, order => order.CustomerId, (customer, order) => new { customer.Name, order.OrderDate });
Any
andAll
: Checks if any or all elements in a sequence satisfy a condition.bool anyPositive = numbers.Any(x => x > 0);
First
,FirstOrDefault
,Last
, andLastOrDefault
: Retrieves the first or last element in a sequence, optionally with a condition.var firstPositive = numbers.First(x => x > 0);
Single
,SingleOrDefault
: Retrieves the single element in a sequence that satisfies a condition.var singlePositive = numbers.Single(x => x > 0);
Set Operations
Union
: Combines two sequences, removing duplicates.var result = sequence1.Union(sequence2);
Intersect
: Returns the common elements between two sequences.var result = sequence1.Intersect(sequence2);
Except
: Returns elements that are present in one sequence but not in another.var result = sequence1.Except(sequence2);
Aggregation
Count
: Returns the number of elements in a sequence.int count = numbers.Count();
Sum
,Min
, andMax
: Calculates the sum, minimum, or maximum value in a sequence.int sum = numbers.Sum();
Average
: Computes the average value of elements in a sequence.double average = numbers.Average();
Aggregate
: Performs a custom aggregation operation on elements in a sequence.var result = numbers.Aggregate((x, y) => x * y);
Conversion
ToList
andToArray
: Converts a sequence to a list or an array.List<int> list = numbers.ToList();
ToDictionary
: Converts a sequence into a dictionary based on key and value selectors.Dictionary<int, string> dict = items.ToDictionary(item => item.Id, item => item.Name);
OfType
: Filters elements of a sequence to include only those of a specific type.var result = mixedObjects.OfType<string>();
Cast
: Casts elements of a sequence to a specified type.var result = mixedObjects.Cast<int>();
Valid C# Statements
Variable Declaration and Assignment:
int x = 10;
string name = "John";
Expression Statements:
x = x + 5;
Console.WriteLine("Hello, World!");
Conditional Statements:
if (condition)
if (condition) { ... }
else
else if (condition) { ... }
switch (variable) { ... }
Loop Statements:
for (int i = 0; i < 10; i++) { ... }
while (condition) { ... }
do { ... } while (condition);
foreach (var item in collection) { ... }
Jump Statements:
break;
continue;
return value;
goto label;
Exception Handling:
try { ... }
catch (ExceptionType ex) { ... }
finally { ... }
throw new Exception("Error message");
Method Calls:
Method();
int result = Add(5, 3);
Object Creation and Initialization:
MyClass obj = new MyClass();
MyClass obj = new MyClass { Property1 = "Value1", Property2 = "Value2" };
Lock Statement:
lock (lockObject) { ... }
Checked and Unchecked Statements:
checked { ... }
unchecked { ... }
Using Statement (for Resource Management):
using (var resource = new Resource()) { ... }
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);
Nullable Types:
int? nullableInt = null;
Switch Expressions (C# 8.0+):
var result = variable switch { ... };
Interpolated Strings (C# 6.0+):
string message = $"Hello, {name}!";
Range and Index Operators (C# 8.0+):
var subArray = myArray[1..4];
Pattern-Based Switch Statements (C# 9.0+):
int result = variable switch { ... };
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 variablex
.string s
: Matches a string and assigns it to variables
.var obj
: Matches any type and assigns it to variableobj
.Var Pattern
var x
: Matches any value and assigns it to variablex
.Wildcard Pattern
_
: Matches any value but discards it.Null Pattern (C# 8.0+)
null
: Matches anull
reference.Property Pattern (C# 8.0+)
Person { Age: 18 }
: Matches aPerson
object with anAge
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 stringname
and an integerage
.Positional Pattern (C# 8.0+)
Point { X: 0, Y: 0 }
: Matches aPoint
object withX
andY
properties set to 0.Rectangle { Width: var w, Height: var h }
: Matches aRectangle
object and assignsWidth
andHeight
tow
andh
.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+)
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 tox
.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 typeint
and assigns it tox
.Binary Patterns (C# 9.0+)
a is b
: Checks ifa
is of typeb
.a as b
: Attempts to casta
to typeb
and returnsnull
if it fails.Parenthesized Patterns (C# 8.0+)
(pattern)
: Groups patterns for precedence.Relational Patterns (C# 9.0+)
a < b
: Matches ifa
is less thanb
.a <= b
: Matches ifa
is less than or equal tob
.a > b
: Matches ifa
is greater thanb
.a >= b
: Matches ifa
is greater than or equal tob
.a == b
: Matches ifa
is equal tob
.a != b
: Matches ifa
is not equal tob
.Valid C# Expressions
Primary Expressions
x
: Identifier (variable or constant).123
: Literal integer."Hello"
: Literal string.true
andfalse
: 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 (returnsnull
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 theBigInteger
class with a value of zero.BigInteger(int value)
: Initializes a new instance of theBigInteger
class with the specified integer value.BigInteger(long value)
: Initializes a new instance of theBigInteger
class with the specified long integer value.BigInteger(byte[] bytes)
: Initializes a new instance of theBigInteger
class from an array of bytes.Static Methods
BigInteger.Add(BigInteger left, BigInteger right)
: Returns the result of adding twoBigInteger
values.BigInteger.Subtract(BigInteger left, BigInteger right)
: Returns the result of subtracting oneBigInteger
value from another.BigInteger.Multiply(BigInteger left, BigInteger right)
: Returns the result of multiplying twoBigInteger
values.BigInteger.Divide(BigInteger dividend, BigInteger divisor)
: Returns the result of dividing oneBigInteger
value by another.BigInteger.Remainder(BigInteger dividend, BigInteger divisor)
: Returns the remainder of dividing oneBigInteger
value by another.BigInteger.Pow(BigInteger value, int exponent)
: Returns aBigInteger
raised to a specified power.BigInteger.Abs(BigInteger value)
: Returns the absolute value of aBigInteger
value.BigInteger.GreatestCommonDivisor(BigInteger left, BigInteger right)
: Returns the greatest common divisor of twoBigInteger
values.BigInteger.Min(BigInteger left, BigInteger right)
: Returns the smaller of twoBigInteger
values.BigInteger.Max(BigInteger left, BigInteger right)
: Returns the larger of twoBigInteger
values.Properties
BitLength
: Gets the number of bits in the two's complement representation of theBigInteger
.IsEven
: Returnstrue
if theBigInteger
is an even number.IsOne
: Returnstrue
if theBigInteger
is equal to 1.IsZero
: Returnstrue
if theBigInteger
is equal to 0.Sign
: Gets a value indicating the sign of theBigInteger
(-1 for negative, 0 for zero, 1 for positive).Conversion Methods
ToByteArray()
: Returns theBigInteger
as a byte array.ToDouble()
: Converts theBigInteger
to a double-precision floating-point number.ToInt32()
: Converts theBigInteger
to a 32-bit signed integer.ToInt64()
: Converts theBigInteger
to a 64-bit signed integer.ToString()
: Converts theBigInteger
to its decimal string representation.The text was updated successfully, but these errors were encountered: