In C#, exclamation marks (!) have multiple uses, depending on the context. Here are some common usages and examples:
-
Logical non-operators: Exclamation marks can be used as logical non-operators to reverse the Boolean value. It will
true
Convert tofalse
,Willfalse
Convert totrue
. Example:
bool isTrue = true; bool isFalse = !isTrue; // isFalseThe value offalse
-
Empty reference check: Exclamation marks can be merged with null values (
?.
) is used together for empty reference checking. It means if the expression on the left isnull
, throw itNullReferenceException
abnormal. Example:
string name = null; string upperCaseName = name!.ToUpper(); // ifnamefornull,Will throwNullReferenceExceptionabnormal
-
Non-null assertion operator: Exclamation marks can be used as non-null assertion operators, and when an expression is known to be not
null
When , you can use an exclamation mark to tell the compiler not to perform empty reference checks. Example:
string message = GetMessageFromExternalSource(); string upperCaseMessage = message!.ToUpper(); // Tell the compilermessageNot fornull,No empty reference checking
- Generic constraints: The exclamation mark can be used as a constraint for a generic type parameter, indicating that the type parameter must be a non-nullable value type. Example:
public class MyClass<T> where T : struct // T must be a non-nullable value type{ // ... }
- Tag name: Exclamation marks can be used as part of the tag name to identify tag statements in the code. Example:
startLoop: for (int i = 0; i < 10; i++) { if (i == 5) goto startLoop; // Jump to the startLoop tag to continue executing the loop}
These are some common usages and examples of exclamation marks in C#. Note that the specific meaning of an exclamation mark depends on the context and may have different uses and behaviors in different situations.
This is the end of this article about some common usages of exclamation marks (!) in C#. For more related C# exclamation mark content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!