C# Features

Last Updated: 12/2/2023

Strings

  • String literals are of type string and can be written in three forms, quoted, verbatim and raw.

Quoted String

string a = "hello";

Verbatim string

  • indicate that a string literal is to be interpreted verbatim (exactly).
  • @ symbol in front of a string to signify that a backslash should not be interpreted as the beginning of an escape sequence.
  • Whitespace is also taken verbatim
  • The only escape sequence the verbatim string does support is "", which signifies a single set of double quotes and does not terminate the string.
// normal string literal
string filename = "c:\\documents\\files\\u0066.txt";

// verbatim string literal
string filename1 = @"c:\documents\files\u0066.txt";

//verbatim string literal - multi line
string multiline = @"first line
       second line
                   third line";    

// special char
string filename2 = @" ""filepath is"" c:\documents\files\u0066.txt";

String Interpolation - C# 6

  • The $ character identifies a string literal as an interpolated string.
  • An interpolated string is a string literal that might contain interpolation expressions.
  • When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results.
  • String interpolation provides a more readable, convenient syntax to format strings.
  • It's easier to read than string composite formatting.

Composite Formatting

var name = "Gandhi";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0} Today is {1}, it's {2} now.", name, date.DayOfWeek, date);
// or
string text = string.format("Hello, {0} Today is {1}, it's {2} now.", name, date.DayOfWeek, date)

String interpolation:

Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date} now.");

Formatting

// formatting
Console.WriteLine($"{Math.PI:F3} - display only three decimal digits of the pi number");

Alignment and Formatting

  • For alignment If positive value passed, the string representation is right-aligned; if negative, it's left-aligned
// right alignment
Console.WriteLine($"{1.25689, 7});
// left alignment
Console.WriteLine($"{1.25689, -7}");
Console.WriteLine($"{1.25689, -7:F2}");

Special Characters

  • To display {,} use double curly braces
string name = "puja"; 
int age = 25;
string message = $"{{hi}}";
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");

Culture-specific formatting

  • Not all cultures use the same format for dates and decimal / currency values.
 double speedOfLight = 299792.458;
 Console.WriteLine(string.Create(
     System.Globalization.CultureInfo.GetCultureInfo("en-IN"), $"The speed of light is {speedOfLight:N3} km/s."));
 Console.WriteLine(string.Create(
     System.Globalization.CultureInfo.GetCultureInfo("nl-NL"), $"The speed of light is {speedOfLight:N3} km/s."));

Verbatim Interpolated string

  • An interpolated verbatim string starts with the both $ and @ characters.
  • You can use $ and @ in any order: both $@and @$ are valid interpolated verbatim strings.
string filename3 = $@" ""filepath is"" {{hi}} {X} c:\documents\files\u0066.txt";
Console.WriteLine(filename3);

Constant Interpolated Strings - C# 10

  • const strings may be initialized using string interpolation if all the placeholders are themselves constant strings.
  • The placeholder expressions can't be numeric constants because those constants are converted to strings at run time.
const string Language = "C#";
const string Platform = ".NET";
const string Version = "10.0";
const string FullProductName = $"{Platform} - Language: {Language} Version: {Version}";

Interpolated string handler

New lines with interpolation expression - C# 11

  • The text inside the characters for a string interpolation can now span multiple lines.
  • The text between the markers is parsed as C#.
  • You can use longer C# expressions, like pattern matching switch expressions, or LINQ queries.
int safetyScore = 75;
string message = $"The usage policy for {safetyScore} is {safetyScore switch
{
    > 90 => "Unlimited usage",
    > 80 => "General usage, with daily safety check",
    > 70 => "Issues must be addressed within 1 week",
    > 50 => "Issues must be addressed within 1 day",
    _ => "Issues must be addressed before continued use",
}}";
Console.WriteLine(message);

Raw String Literal - C# 11

  • Raw string literals can contain arbitrary text without requiring escape sequences.
  • Raw string literals can include whitespace and new lines, embedded quotes, and other special characters.
  • Raw string literals are enclosed in a minimum of three double quotation marks ("""):
  • Raw string literals typically have the starting and ending quote sequences on separate lines from the embedded text.
  • The ending quote count must match the begin quote count.
  • All whitespace to the left of the closing triple quotes—for all lines of the raw string literal—is removed.
  • Allows direct placement of JSON strings into C# programs without complex and error-prone escape sequences.
  • Representing regular expressions within C# is another format where raw string literals prove extremely helpful

Three Double Quotation

 var text1 = """
This is a multi-line
    string literal with the second line indented.
""";
Console.WriteLine(text1);

More Double Quotation

  • You can even include a sequence of three (or more) double quote characters.
var text2 = """""
This raw string literal has four """", count them: """" four!
embedded quote characters in a sequence. That's why it starts and ends
with five double quotes.

You could extend this example with as many embedded quotes as needed for your text.
""""";
Console.WriteLine(text2);

String Interpolation

  • . To enclose any interpolation expression within that string, you need to use the same number of braces as the number of $ characters
int X = 2;
int Y = 3;
var pointMessage2 = $$"""{The point {{{X}}, {{Y}}} is {{Math.Sqrt(X * X + Y * Y):F3}} from the origin}""";
var json = $$"""
		   {
		   "id": 1,
		   "name": "siva"
		   "x": {{x}}
		   }	
           """;

NewLine

  • In windows new line is \r\n, In linux it is \n
  • Use System.Console.WriteLine() and System.Environment.NewLine for NewLine
Console.Write($"First line {Environment.NewLine} Second Line");

Nullable Reference Type

  • Prior to C# 8.0, since all reference types were nullable by default
  • In C# 8.0, the behavior can be configured such that reference types could be declared as nullable with the nullable modifier or default to not null.
string firstName;
string? middleName;

Setting Nullable

  • Prior to .NET 6, new projects use the default, <Nullable>disable</Nullable>.
  • Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file.
  • There are two ways to control the nullable context. At the project level, you can add the <Nullable>enable</Nullable> project setting. In a single C# source file, you can add the #nullable enable pragma to enable the nullable context.

References