2 C# Core Language Features
2 C# Core Language Features
using System;
namespace Donis.CSharpBook {
class Starter{
#if DEBUGGING
static void OutputLocals() {
Console.WriteLine("debugging...");
}
#endif
static void Main() {
#if DEBUGGING
OutputLocals();
#endif
}
}
}
• Finally, the #elif directive essentially nests #if
conditional preprocessor directives:
#if expression
source_code
#elif expression
source_code
#else
source_code
#endif
Example – Consoleapplication3
• Preprocessor directives help the developer to
make programming with minimal complexity,
improving readability, ease Of maintenance,
and prompting invalid changes in the flow of
code, etc.
Diagnostic directives
• Diagnostic directives include the
– #error,
– #warning,
– #pragma directives.
• The #error and #warning directives display error
and warning messages, correspondingly.
• The diagnostic messages are displayed in the Error
List window of the Visual Studio IDE.
• Similar to standard compilation errors,
– an #error directive prevents the program from
compiling;
– a #warning directive does not prevent the program
from successfully compiling.
• Use conditional directives to conditionally apply
diagnostic directives.
• Diagnostic directives:
– #error error_message
– #warning error_message
• The error_message is of string type and is
optional.
Example – errordirective
• Example – warningdirective
• The #pragma directive enables or disables
standard compilation warnings.
• Pragma directives:
– #pragma warning disable warning_list
– #pragma warning restore warning_list
• The warning_list contains one or more warnings
delimited with commas.
• The status of a warning included in the warning_list
remains unchanged until the end of the compilation
unit unless altered in a later #error directive.
• This #pragma directive disables the 219 warning,
which is the "variable is assigned but its value is
never used" warning:
#pragma warning disable 219
class Starter{
static void Main() {
int variablea=10;
}
}
Example pragmadirective
Region directives
• Region directives mark sections of source
code.
• The #region directive starts a region, whereas
the #endregion directive ends the region.
• Region directives can be nested.
• The Visual Studio IDE outlines the source code
using region tags.
• In Visual Studio, you can collapse or expand
regions of source code.
Region directives:
#region identity
source_code
#endregion
Example regiondirective
• This directive organizes code.
• We create named "regions" of code,
terminated with endregion.
• We can then collapse these regions in Visual
Studio.
Line directives
• Line directives modify the line number reported in
subsequent compiler errors and warnings.
• There are three versions of the line directive.
– #line line_number source_filename
– #line default
– #line hidden
• The first #line directive shown renumbers the
source code from the location of the directive
until the end of the compilation unit is reached or
overridden by another #line directive.
• In the following code, the #line directive resets the
current line to 25:
#line 25
static void Main() {
Console.WriteLine("#line application");
int variablea=10; // 219 warning
}
• The second type of #line directive resets or
undoes any previous #line directive.
• The line number is reset to the natural line
number.
• The third #line directive is only tangentially
related to the line number.
• This directive does not affect the line number;
it hides source code from the debugger.
• Excluding another #line hidden directive, the
source code is hidden until the next #line
directive is encountered.
Example linedirective1
Blocks
class NodeInt {
public NodeInt(int f_Value, NodeInt f_Previous) {
m_Value=f_Value;
m_Previous=f_Previous;
}
// Remaining methods
class Node<T> {
public Node(T f_Value, Node<T> f_Previous) {
m_Value=f_Value;
m_Previous=f_Previous;
}
// Remaining methods
private T m_Value;
private Node<T> m_Previous;
}
• The generics symbol T bounds the type parameters
• discussed in detail later
Nullable Types
• Nullable types are value types that can be
assigned a null value.
• Nullable types provide a consistent
mechanism for determining whether a value
type is empty (null).
• Nullable type:
valuetype? identifier;
• discussed in detail later
Characters
• C# source files contain Unicode characters,
which are the most innate of symbols.
• Every element, keyword, operator, or identifier
in the source file is a composite of Unicode
characters.
Numeric Suffixes
• Numeric suffixes cast a literal value to a
related type.
• Literal integer values can have the
– L, U, UL, and LU suffixes appended to them;
• literal real values can have
– F, D, and M suffixes added.
• The suffixes are case insensitive.
Description of Suffixes
• Description Type Suffix
• Unsigned integer or unsigned long unit or long u
• Long or unsigned long long or ulong l
• Unsigned long ulong ul
• Float float f
• Double double d
• Money decimal m
Escape Characters
• The escape character provides an alternate means of
encoding Unicode characters, especially special characters
that are not available on a standard keyboard.
• Escape sequences can be used as characters within
identifiers and elsewhere.
• Unicode escape sequences must have four hexadecimal
digits and are therefore limited to a single character.
• Escape sequence:
\uhexadecimal digit1 digit2 digit3 digit4
• Hexadecimal escape sequences define one or more Unicode
characters and contain one or more digits.
• Hexadecimal sequence:
\xhexadecimal digit1 digit2 digitn
Predefined Escape Sequences
• Simple Escape Sequence
• Single quote \'
• Double quote \"
• Backlash \\
• Null \0
• Alert \a
• Backspace \b
• Form feed \f
• New line \n
• Carriage return \r
• Horizontal tab \t
• Unicode character \u
• Vertical tab \v
• Hexadecimal character(s) \x
Verbatim Characters
• The verbatim character prevents the translation of a
string or identifier, where it is treated "as-is."
• To create a verbatim string or identifier, prefix it with
the verbatim character.
• A verbatim string is a string literal prefixed with the
verbatim character.
• The characters of the verbatim string, including escape
sequences, are not translated.
• The exception is the quote escape character, which is
translated even in a verbatim string.
• Unlike a normal string, verbatim strings can contain
physical line feeds.
A sample verbatim string:
class Verbatim{
static void Main() {
string fileLocation=@"c:\datafile.txt";
Console.WriteLine("File is located at {0}",
fileLocation);
}
}
• A verbatim identifier is an identifier prefixed with
the verbatim character that prevents the identifier
from being parsed as a keyword.
• Although this is of limited usefulness, porting
source code from another language—in which the
keywords are different—is a circumstance in
which verbatim identifiers might be helpful.
• Otherwise, it is a best practice not to use this
language feature because verbatim identifiers
make your code less readable and harder to
maintain.
• This is a partial translation of French to English:
L'espoir is a waking dream.
• Can you decipher this sentence? Unless you are fluent in French,
the partial translation is ineffectual at best.
• The original sentence was ''L'espoir est un rêve de réveil."
• The following is an equally unskillful translation, although
technically acceptable:
}
• assuming that FunctionA returns false, the
entire expression evaluates to false.
• Therefore, the expression short-circuits and
FunctionB is not invoked.
List of Boolean Operators
• Operator Symbol
• Equals ==
• Not Equal !=
• Less Than <
• Greater Than >
• And (Short Circuiting) &&
• Or (Short Circuiting) ||
• And &
• Or |
• Less Than or Equal <=
• Greater Than or Equal >=
• Logical XOR ^
Ternary operators
• The conditional operator is the sole ternary
operator in C# and is an abbreviated if else
statement.
Conditional operator:
boolean_expression?truth_statement:false_statement
• Example :
variable>5?Console.WriteLine(">5"):Console.WriteLine("<= 5");
Pointer operators
• Pointer operators are available in unsafe mode
and support conventional pointers.
• The unsafe compiler option builds a program
in unsafe mode.
• Alternatively, in Visual Studio IDE, set the
Allow Unsafe Mode option on the Build Page
of Project Settings.
List of Pointer Operators
• Operator Symbol Description
• Asterisk Operator1 * Declare a pointer
• Asterisk Operator2 * Dereference a pointer
• Ampersand Operator & Obtain an address
• Arrow Operator -> Dereference a pointer and
member access
sample code using pointers
static void Main(string[] args)
{
unsafe {
int variable = 10;
int* pVariable = &variable;
Console.WriteLine("Value at address is {0}.",
*pVariable);
}
}
• The above code must be compiled with the unsafe
compiler option on.
Identifiers