Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/skills/csharp-snippet-modernization/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ Apply these changes when they preserve behavior and sample clarity:
`System` namespaces first.
- Put curly braces on their own lines.
- Normalize indentation, spacing, trailing whitespace, and final newlines.
- Use null-propagation instead of explicit null checks.
- Remove `this.` where it's unnecessary.
- Add `using` statements for disposable types, and remove redundant calls to `Close()` or `Dispose()`.
- Prune unnecessary package references from project files.

Don't introduce `var`; this repository prefers explicit types.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>

</Project>
143 changes: 143 additions & 0 deletions snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// <SnippetUsings>
using System;
using System.Buffers;
using System.Globalization;
using System.Text;
// </SnippetUsings>

namespace SearchValuesExamples;

public static class Validation
{
// <SnippetValidation>
// Cache the SearchValues instance in a static readonly field so that the
// optimized representation is computed once and reused for every search.
private static readonly SearchValues<char> s_hexDigits =
SearchValues.Create("0123456789ABCDEFabcdef");

// Rejects any value that contains a character outside of the allowed set.
public static bool IsHexString(ReadOnlySpan<char> value) =>
value.Length % 2 == 0 && !value.ContainsAnyExcept(s_hexDigits);
// </SnippetValidation>
}

public static class Escaping
{
// <SnippetEscaping>
private static readonly SearchValues<char> s_charsToEscape = SearchValues.Create("\"\\\b\f\n\r\t");

public static void AppendEscaped(StringBuilder builder, ReadOnlySpan<char> value)
{
while (true)
{
// Find the next character that needs special treatment.
// IndexOfAny returns -1 when none of the values are present.
int index = value.IndexOfAny(s_charsToEscape);
if (index < 0)
{
builder.Append(value);
return;
}

// Everything up to that point can be copied in bulk.
builder.Append(value[..index]);

builder.Append('\\');
builder.Append(value[index] switch
{
'\b' => 'b',
'\f' => 'f',
'\n' => 'n',
'\r' => 'r',
'\t' => 't',
char c => c,
});

value = value[(index + 1)..];
}
}
// </SnippetEscaping>
}

public static class Bytes
{
// <SnippetBytes>
// Bytes that separate fields in the UTF-8 log lines this app reads.
// A UTF-8 literal ("u8") avoids allocating a string just to create the set.
private static readonly SearchValues<byte> s_delimiters = SearchValues.Create("\t ,;:|="u8);

// Finds where the next field ends, or -1 when the last field is reached.
public static int IndexOfNextDelimiter(ReadOnlySpan<byte> utf8Line) =>
utf8Line.IndexOfAny(s_delimiters);
// </SnippetBytes>
}

public static class Strings
{
// <SnippetStrings>
private static readonly SearchValues<string> s_schemes =
SearchValues.Create(["http://", "https://", "ftp://"], StringComparison.OrdinalIgnoreCase);

// Finds the position of the first substring in the set, ignoring case.
public static int IndexOfScheme(ReadOnlySpan<char> text) =>
text.IndexOfAny(s_schemes);
// </SnippetStrings>
}

public static class SingleString
{
// <SnippetSingleString>
private static readonly SearchValues<string> s_chunked =
SearchValues.Create(["chunked"], StringComparison.OrdinalIgnoreCase);

// Equivalent to text.IndexOf("chunked", StringComparison.OrdinalIgnoreCase),
// but faster because the value is analyzed once when the instance is created.
public static int IndexOfChunked(ReadOnlySpan<char> text) =>
text.IndexOfAny(s_chunked);
// </SnippetSingleString>
}

public static class SingleValues
{
// <SnippetContains>
// The prefix that starts an escape sequence. A single-value SearchValues<string>
// is a faster alternative to IndexOf(value, StringComparison).
private static readonly SearchValues<string> s_escapePrefix =
SearchValues.Create(["\\u"], StringComparison.Ordinal);

// Characters that aren't allowed to appear unescaped in the output.
private static readonly SearchValues<char> s_mustStayEscaped = SearchValues.Create("\"\\\b\f\n\r\t");

// Turns "\uXXXX" sequences back into the characters they represent, but
// keeps the ones that must stay escaped as they are.
public static void AppendDecoded(StringBuilder builder, ReadOnlySpan<char> value)
{
while (true)
{
int index = value.IndexOfAny(s_escapePrefix);
if (index < 0 || value.Length - index < 6)
{
builder.Append(value);
return;
}

builder.Append(value[..index]);

ReadOnlySpan<char> escaped = value.Slice(index, 6);
value = value[(index + 6)..];

// The decoded character is computed one at a time, so there's no span
// to search and Contains is the right choice here.
if (!ushort.TryParse(escaped[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort decoded) ||
s_mustStayEscaped.Contains((char)decoded))
{
builder.Append(escaped);
}
else
{
builder.Append((char)decoded);
}
}
}
// </SnippetContains>
}
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
//<Snippet1>
using System;
using System.CodeDom;

namespace CodeDomSamples
{
public class CodeArgumentReferenceExpressionExample
{
public CodeArgumentReferenceExpressionExample()
{
{
//<Snippet2>
// Declare a method that accepts a string parameter named text.
CodeMemberMethod cmm = new CodeMemberMethod();
cmm.Parameters.Add( new CodeParameterDeclarationExpression("String", "text") );
cmm.Parameters.Add(new CodeParameterDeclarationExpression("String", "text"));
cmm.Name = "WriteString";
cmm.ReturnType = new CodeTypeReference("System.Void");

// Create a method invoke statement to output the string passed to the method.
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeArgumentReferenceExpression("text") );
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeArgumentReferenceExpression("text"));

// Add the method invoke expression to the method's statements collection.
cmm.Statements.Add( cmie );
cmm.Statements.Add(cmie);

// A C# code generator produces the following source code for the preceeding example code:
// private void WriteString(String text)
// {
// Console.WriteLine(text);
// }
//</Snippet2>
}
//</Snippet2>
}
}
}
//</Snippet1>
//</Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

</Project>
Loading
Loading