diff --git a/.github/skills/csharp-snippet-modernization/SKILL.md b/.github/skills/csharp-snippet-modernization/SKILL.md index eeffbf9e23f..6c4c4f8b198 100644 --- a/.github/skills/csharp-snippet-modernization/SKILL.md +++ b/.github/skills/csharp-snippet-modernization/SKILL.md @@ -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. diff --git a/snippets/csharp/System.Buffers/SearchValues/Overview/Project.csproj b/snippets/csharp/System.Buffers/SearchValues/Overview/Project.csproj new file mode 100644 index 00000000000..dfdef3fd2a7 --- /dev/null +++ b/snippets/csharp/System.Buffers/SearchValues/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs b/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs new file mode 100644 index 00000000000..0e2a01a124d --- /dev/null +++ b/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs @@ -0,0 +1,143 @@ +// +using System; +using System.Buffers; +using System.Globalization; +using System.Text; +// + +namespace SearchValuesExamples; + +public static class Validation +{ + // + // 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 s_hexDigits = + SearchValues.Create("0123456789ABCDEFabcdef"); + + // Rejects any value that contains a character outside of the allowed set. + public static bool IsHexString(ReadOnlySpan value) => + value.Length % 2 == 0 && !value.ContainsAnyExcept(s_hexDigits); + // +} + +public static class Escaping +{ + // + private static readonly SearchValues s_charsToEscape = SearchValues.Create("\"\\\b\f\n\r\t"); + + public static void AppendEscaped(StringBuilder builder, ReadOnlySpan 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)..]; + } + } + // +} + +public static class Bytes +{ + // + // 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 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 utf8Line) => + utf8Line.IndexOfAny(s_delimiters); + // +} + +public static class Strings +{ + // + private static readonly SearchValues 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 text) => + text.IndexOfAny(s_schemes); + // +} + +public static class SingleString +{ + // + private static readonly SearchValues 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 text) => + text.IndexOfAny(s_chunked); + // +} + +public static class SingleValues +{ + // + // The prefix that starts an escape sequence. A single-value SearchValues + // is a faster alternative to IndexOf(value, StringComparison). + private static readonly SearchValues s_escapePrefix = + SearchValues.Create(["\\u"], StringComparison.Ordinal); + + // Characters that aren't allowed to appear unescaped in the output. + private static readonly SearchValues 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 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 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); + } + } + } + // +} diff --git a/snippets/csharp/System.CodeDom/CodeArgumentReferenceExpression/Overview/codeargumentreferenceexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeArgumentReferenceExpression/Overview/codeargumentreferenceexpressionexample.cs index 7546b5418d0..1172b45b6c4 100644 --- a/snippets/csharp/System.CodeDom/CodeArgumentReferenceExpression/Overview/codeargumentreferenceexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeArgumentReferenceExpression/Overview/codeargumentreferenceexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -7,27 +6,27 @@ namespace CodeDomSamples public class CodeArgumentReferenceExpressionExample { public CodeArgumentReferenceExpressionExample() - { + { // // 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); // } - // - } + // + } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/Project.csproj new file mode 100644 index 00000000000..4a6d98d26b7 --- /dev/null +++ b/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/Project.csproj @@ -0,0 +1,9 @@ + + + + Exe + net10.0-windows + true + + + diff --git a/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs b/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs index fbd5e645949..594742f73c0 100644 --- a/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs +++ b/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs @@ -2,32 +2,24 @@ using System; using System.CodeDom; using System.CodeDom.Compiler; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; -using System.Data; using System.IO; -using Microsoft.CSharp; -using Microsoft.VisualBasic; -using Microsoft.JScript; +using System.Windows.Forms; namespace CodeDOMSamples { /// /// Provides a wrapper for CodeDOM samples. /// - public class Form1 : System.Windows.Forms.Form + public class Form1 : Form { - private System.CodeDom.CodeCompileUnit cu; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.Button button2; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.RadioButton radioButton1; - private System.Windows.Forms.RadioButton radioButton2; - private System.Windows.Forms.RadioButton radioButton3; - private int language = 1; // 1 = Csharp 2 = VB 3 = JScript + private CodeCompileUnit cu; + private TextBox textBox1; + private Button button1; + private Button button2; + private GroupBox groupBox1; + private RadioButton radioButton1; + private RadioButton radioButton2; + private int language = 1; // 1 = C# 2 = VB private System.ComponentModel.Container components = null; public Form1() @@ -41,23 +33,33 @@ public Form1() public CodeCompileUnit CreateGraph() { // Create a compile unit to contain a CodeDOM graph - CodeCompileUnit cu = new CodeCompileUnit(); + CodeCompileUnit cu = new(); + + // Create a namespace named "Samples" + CodeNamespace cn = new("Samples"); - // Create a namespace named "TestSpace" - CodeNamespace cn = new CodeNamespace("TestSpace"); + // Import the System namespace + cn.Imports.Add(new CodeNamespaceImport("System")); // Create a new type named "TestClass" - CodeTypeDeclaration cd = new CodeTypeDeclaration("TestClass"); + CodeTypeDeclaration cd = new("TestClass"); // Create a new entry point method - CodeEntryPointMethod cm = new CodeEntryPointMethod(); + CodeEntryPointMethod cm = new(); + + // Write "Hello World!" to the console + CodeMethodInvokeExpression writeLine = new( + new CodeTypeReferenceExpression("System.Console"), + "WriteLine", + new CodePrimitiveExpression("Hello World!")); + cm.Statements.Add(writeLine); // // Create an initialization expression for a new array of type Int32 with 10 indices - CodeArrayCreateExpression ca1 = new CodeArrayCreateExpression("System.Int32", 10); + CodeArrayCreateExpression ca1 = new("System.Int32", 10); // Declare an array of type Int32, using the CodeArrayCreateExpression ca1 as the initialization expression - CodeVariableDeclarationStatement cv1 = new CodeVariableDeclarationStatement("System.Int32[]", "x", ca1); + CodeVariableDeclarationStatement cv1 = new("System.Int32[]", "x", ca1); // A C# code generator produces the following source code for the preceeding example code: @@ -67,59 +69,77 @@ public CodeCompileUnit CreateGraph() // Add the variable declaration and initialization statement to the entry point method cm.Statements.Add(cv1); + // + // Declare a variable of type Int32 named "i" + CodeVariableDeclarationStatement cv2 = new("System.Int32", "i"); + cm.Statements.Add(cv2); + + // Assign the value 10 to the integer variable "i" + CodeAssignStatement assignment = new(new CodeVariableReferenceExpression("i"), new CodePrimitiveExpression(10)); + + // A C# code generator produces the following source code for the preceding example code: + + // i = 10; + // + + cm.Statements.Add(assignment); + + // + // Create an array indexer expression that references index 5 of array "x" + CodeArrayIndexerExpression ci1 = new(new CodeVariableReferenceExpression("x"), new CodePrimitiveExpression(5)); + + // A C# code generator produces the following source code for the preceding example code: + + // x[5] + // + + // Declare a variable of type Int32 and assign the value of the array indexer to it + CodeVariableDeclarationStatement cv3 = new("System.Int32", "y", ci1); + cm.Statements.Add(cv3); + // Add the entry point method to the "TestClass" type cd.Members.Add(cm); // Add the "TestClass" type to the namespace cn.Types.Add(cd); - // Add the "TestSpace" namespace to the compile unit + // Add the "Samples" namespace to the compile unit cu.Namespaces.Add(cn); return cu; } // + // private void OutputGraph() { // Create string writer to output to textbox - StringWriter sw = new StringWriter(); + StringWriter sw = new(); // Create appropriate CodeProvider - System.CodeDom.Compiler.CodeDomProvider cp; - switch(language) + CodeDomProvider cp = language switch { - case 2: // VB - cp = CodeDomProvider.CreateProvider("VisualBasic"); - break; - case 3: // JScript - cp = CodeDomProvider.CreateProvider("JScript"); - break; - default: // CSharp - cp = CodeDomProvider.CreateProvider("CSharp"); - break; - } - - // Create a code generator that will output to the string writer - ICodeGenerator cg = cp.CreateGenerator(sw); + // VB + 2 => CodeDomProvider.CreateProvider("VisualBasic"), + // CSharp + _ => CodeDomProvider.CreateProvider("CSharp"), + }; // Generate code from the compile unit and outputs it to the string writer - cg.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions()); + cp.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions()); // Output the contents of the string writer to the textbox - this.textBox1.Text = sw.ToString(); + textBox1.Text = sw.ToString(); } + // - protected override void Dispose( bool disposing ) + protected override void Dispose(bool disposing) { - if( disposing ) + if (disposing) { - if (components != null) - { - components.Dispose(); - } + components?.Dispose(); } - base.Dispose( disposing ); + base.Dispose(disposing); } #region Windows Form Designer generated code @@ -129,97 +149,81 @@ protected override void Dispose( bool disposing ) /// private void InitializeComponent() { - this.textBox1 = new System.Windows.Forms.TextBox(); - this.button1 = new System.Windows.Forms.Button(); - this.button2 = new System.Windows.Forms.Button(); - this.groupBox1 = new System.Windows.Forms.GroupBox(); - this.radioButton1 = new System.Windows.Forms.RadioButton(); - this.radioButton2 = new System.Windows.Forms.RadioButton(); - this.radioButton3 = new System.Windows.Forms.RadioButton(); - this.groupBox1.SuspendLayout(); - this.SuspendLayout(); + textBox1 = new TextBox(); + button1 = new Button(); + button2 = new Button(); + groupBox1 = new GroupBox(); + radioButton1 = new RadioButton(); + radioButton2 = new RadioButton(); + groupBox1.SuspendLayout(); + SuspendLayout(); // // textBox1 // - this.textBox1.Location = new System.Drawing.Point(16, 112); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBox1.Size = new System.Drawing.Size(664, 248); - this.textBox1.TabIndex = 0; - this.textBox1.Text = ""; - this.textBox1.WordWrap = false; + textBox1.Location = new System.Drawing.Point(16, 112); + textBox1.Multiline = true; + textBox1.Name = "textBox1"; + textBox1.ScrollBars = ScrollBars.Both; + textBox1.Size = new System.Drawing.Size(664, 248); + textBox1.TabIndex = 0; + textBox1.Text = ""; + textBox1.WordWrap = false; // // button1 // - this.button1.BackColor = System.Drawing.Color.Aquamarine; - this.button1.Location = new System.Drawing.Point(16, 16); - this.button1.Name = "button1"; - this.button1.TabIndex = 1; - this.button1.Text = "Generate"; - this.button1.Click += new System.EventHandler(this.button1_Click); + button1.BackColor = System.Drawing.Color.Aquamarine; + button1.Location = new System.Drawing.Point(16, 16); + button1.Name = "button1"; + button1.TabIndex = 1; + button1.Text = "Generate"; + button1.Click += new System.EventHandler(button1_Click); // // button2 // - this.button2.BackColor = System.Drawing.Color.MediumTurquoise; - this.button2.Location = new System.Drawing.Point(112, 16); - this.button2.Name = "button2"; - this.button2.TabIndex = 2; - this.button2.Text = "Show Code"; - this.button2.Click += new System.EventHandler(this.button2_Click); + button2.BackColor = System.Drawing.Color.MediumTurquoise; + button2.Location = new System.Drawing.Point(112, 16); + button2.Name = "button2"; + button2.TabIndex = 2; + button2.Text = "Clear Code"; + button2.Click += new System.EventHandler(button2_Click); // // groupBox1 // - this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] { - this.radioButton3, - this.radioButton2, - this.radioButton1}); - this.groupBox1.Location = new System.Drawing.Point(16, 48); - this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(384, 56); - this.groupBox1.TabIndex = 3; - this.groupBox1.TabStop = false; - this.groupBox1.Text = "Language selection"; + groupBox1.Controls.AddRange([radioButton2, radioButton1]); + groupBox1.Location = new System.Drawing.Point(16, 48); + groupBox1.Name = "groupBox1"; + groupBox1.Size = new System.Drawing.Size(384, 56); + groupBox1.TabIndex = 3; + groupBox1.TabStop = false; + groupBox1.Text = "Language selection"; // // radioButton1 // - this.radioButton1.Checked = true; - this.radioButton1.Location = new System.Drawing.Point(16, 24); - this.radioButton1.Name = "radioButton1"; - this.radioButton1.TabIndex = 0; - this.radioButton1.TabStop = true; - this.radioButton1.Text = "CSharp"; - this.radioButton1.Click += new System.EventHandler(this.radioButton1_CheckedChanged); + radioButton1.Checked = true; + radioButton1.Location = new System.Drawing.Point(16, 24); + radioButton1.Name = "radioButton1"; + radioButton1.TabIndex = 0; + radioButton1.TabStop = true; + radioButton1.Text = "CSharp"; + radioButton1.Click += new System.EventHandler(radioButton1_CheckedChanged); // // radioButton2 // - this.radioButton2.Location = new System.Drawing.Point(144, 24); - this.radioButton2.Name = "radioButton2"; - this.radioButton2.TabIndex = 1; - this.radioButton2.Text = "Visual Basic"; - this.radioButton2.Click += new System.EventHandler(this.radioButton2_CheckedChanged); - // - // radioButton3 - // - this.radioButton3.Location = new System.Drawing.Point(272, 24); - this.radioButton3.Name = "radioButton3"; - this.radioButton3.TabIndex = 2; - this.radioButton3.Text = "JScript"; - this.radioButton3.Click += new System.EventHandler(this.radioButton3_CheckedChanged); + radioButton2.Location = new System.Drawing.Point(144, 24); + radioButton2.Name = "radioButton2"; + radioButton2.TabIndex = 1; + radioButton2.Text = "Visual Basic"; + radioButton2.Click += new System.EventHandler(radioButton2_CheckedChanged); // // Form1 // - this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); - this.ClientSize = new System.Drawing.Size(714, 367); - this.Controls.AddRange(new System.Windows.Forms.Control[] { - this.groupBox1, - this.button2, - this.button1, - this.textBox1}); - this.Name = "Form1"; - this.Text = "CodeDOM Samples Framework"; - this.groupBox1.ResumeLayout(false); - this.ResumeLayout(false); + AutoScaleBaseSize = new System.Drawing.Size(5, 13); + ClientSize = new System.Drawing.Size(714, 367); + Controls.AddRange([groupBox1, button2, button1, textBox1]); + Name = "Form1"; + Text = "CodeDOM Samples Framework"; + groupBox1.ResumeLayout(false); + ResumeLayout(false); } #endregion @@ -229,52 +233,40 @@ static void Main() Application.Run(new Form1()); } - private void ShowCode() + private void ClearCode() { - this.textBox1.Text=""; + textBox1.Text = ""; } // Show code button - private void button2_Click(object sender, System.EventArgs e) + private void button2_Click(object sender, EventArgs e) { - ShowCode(); + ClearCode(); } // Generate and show code button - private void button1_Click(object sender, System.EventArgs e) + private void button1_Click(object sender, EventArgs e) { OutputGraph(); } // Csharp language selection button - private void radioButton1_CheckedChanged(object sender, System.EventArgs e) + private void radioButton1_CheckedChanged(object sender, EventArgs e) { - radioButton1.Checked=true; - radioButton2.Checked=false; - radioButton3.Checked=false; + radioButton1.Checked = true; + radioButton2.Checked = false; - language=1; + language = 1; } // Visual Basic language selection button - private void radioButton2_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=false; - radioButton2.Checked=true; - radioButton3.Checked=false; - - language=2; - } - - // JScript language selection button - private void radioButton3_CheckedChanged(object sender, System.EventArgs e) + private void radioButton2_CheckedChanged(object sender, EventArgs e) { - radioButton1.Checked=false; - radioButton2.Checked=false; - radioButton3.Checked=true; + radioButton1.Checked = false; + radioButton2.Checked = true; - language=3; + language = 2; } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeArrayIndexerExpression/Overview/codearrayindexerexpressionsnippet.cs b/snippets/csharp/System.CodeDom/CodeArrayIndexerExpression/Overview/codearrayindexerexpressionsnippet.cs deleted file mode 100644 index d5fdcc5ba28..00000000000 --- a/snippets/csharp/System.CodeDom/CodeArrayIndexerExpression/Overview/codearrayindexerexpressionsnippet.cs +++ /dev/null @@ -1,293 +0,0 @@ -// -using System; -using System.CodeDom; -using System.CodeDom.Compiler; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; -using System.Data; -using System.IO; -using Microsoft.CSharp; -using Microsoft.VisualBasic; -using Microsoft.JScript; - -namespace CodeDOMSamples -{ - /// - /// Provides a wrapper for CodeDOM samples. - /// - public class Form1 : System.Windows.Forms.Form - { - private System.CodeDom.CodeCompileUnit cu; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.Button button2; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.RadioButton radioButton1; - private System.Windows.Forms.RadioButton radioButton2; - private System.Windows.Forms.RadioButton radioButton3; - private int language = 1; // 1 = Csharp 2 = VB 3 = JScript - private System.ComponentModel.Container components = null; - - public Form1() - { - InitializeComponent(); - - cu = CreateGraph(); - } - - // - public CodeCompileUnit CreateGraph() - { - // Create a compile unit to contain a CodeDOM graph - CodeCompileUnit cu = new CodeCompileUnit(); - - // Create a namespace named "TestSpace" - CodeNamespace cn = new CodeNamespace("TestSpace"); - - // Create a new type named "TestClass" - CodeTypeDeclaration cd = new CodeTypeDeclaration("TestClass"); - - // Create an entry point method - CodeEntryPointMethod cm = new CodeEntryPointMethod(); - - // Create the initialization expression for an array of type Int32 with 10 indices - CodeArrayCreateExpression ca1 = new CodeArrayCreateExpression("System.Int32", 10); - - // Declare an array of type Int32, using the CodeArrayCreateExpression ca1 as the initialization expression - CodeVariableDeclarationStatement cv1 = new CodeVariableDeclarationStatement("System.Int32[]", "x", ca1); - - // Add the array declaration and initialization statement to the entry point method class member - cm.Statements.Add(cv1); - - // - // Create an array indexer expression that references index 5 of array "x" - CodeArrayIndexerExpression ci1 = new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("x"), new CodePrimitiveExpression(5)); - - // A C# code generator produces the following source code for the preceeding example code: - - // x[5] - // - - // Declare a variable of type Int32 and adds it to the entry point method - CodeVariableDeclarationStatement cv2 = new CodeVariableDeclarationStatement("System.Int32", "y"); - cm.Statements.Add(cv2); - - // Assign the value of the array indexer ci1 to variable "y" - CodeAssignStatement as1 = new CodeAssignStatement(new CodeVariableReferenceExpression("y"), ci1); - - // Add the assignment statement to the entry point method - cm.Statements.Add(as1); - - // Add the entry point method to the "TestClass" type - cd.Members.Add(cm); - - // Add the "TestClass" type to the namespace - cn.Types.Add(cd); - - // Add the "TestSpace" namespace to the compile unit - cu.Namespaces.Add(cn); - - return cu; - } - // - - private void OutputGraph() - { - // Create string writer to output to textbox - StringWriter sw = new StringWriter(); - - // Create appropriate CodeProvider - System.CodeDom.Compiler.CodeDomProvider cp; - switch(language) - { - case 2: // VB - cp = CodeDomProvider.CreateProvider("VisualBasic"); - break; - case 3: // JScript - cp = CodeDomProvider.CreateProvider("JScript"); - break; - default: // CSharp - cp = CodeDomProvider.CreateProvider("CSharp"); - break; - } - - // Create a code generator that will output to the string writer - ICodeGenerator cg = cp.CreateGenerator(sw); - - // Generate code from the compile unit and outputs it to the string writer - cg.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions()); - - // Output the contents of the string writer to the textbox - this.textBox1.Text = sw.ToString(); - } - - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - if (components != null) - { - components.Dispose(); - } - } - base.Dispose( disposing ); - } - - #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.textBox1 = new System.Windows.Forms.TextBox(); - this.button1 = new System.Windows.Forms.Button(); - this.button2 = new System.Windows.Forms.Button(); - this.groupBox1 = new System.Windows.Forms.GroupBox(); - this.radioButton1 = new System.Windows.Forms.RadioButton(); - this.radioButton2 = new System.Windows.Forms.RadioButton(); - this.radioButton3 = new System.Windows.Forms.RadioButton(); - this.groupBox1.SuspendLayout(); - this.SuspendLayout(); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(16, 112); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBox1.Size = new System.Drawing.Size(664, 248); - this.textBox1.TabIndex = 0; - this.textBox1.Text = ""; - this.textBox1.WordWrap = false; - // - // button1 - // - this.button1.BackColor = System.Drawing.Color.Aquamarine; - this.button1.Location = new System.Drawing.Point(16, 16); - this.button1.Name = "button1"; - this.button1.TabIndex = 1; - this.button1.Text = "Generate"; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // button2 - // - this.button2.BackColor = System.Drawing.Color.MediumTurquoise; - this.button2.Location = new System.Drawing.Point(112, 16); - this.button2.Name = "button2"; - this.button2.TabIndex = 2; - this.button2.Text = "Show Code"; - this.button2.Click += new System.EventHandler(this.button2_Click); - // - // groupBox1 - // - this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] { - this.radioButton3, - this.radioButton2, - this.radioButton1}); - this.groupBox1.Location = new System.Drawing.Point(16, 48); - this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(384, 56); - this.groupBox1.TabIndex = 3; - this.groupBox1.TabStop = false; - this.groupBox1.Text = "Language selection"; - // - // radioButton1 - // - this.radioButton1.Checked = true; - this.radioButton1.Location = new System.Drawing.Point(16, 24); - this.radioButton1.Name = "radioButton1"; - this.radioButton1.TabIndex = 0; - this.radioButton1.TabStop = true; - this.radioButton1.Text = "CSharp"; - this.radioButton1.Click += new System.EventHandler(this.radioButton1_CheckedChanged); - // - // radioButton2 - // - this.radioButton2.Location = new System.Drawing.Point(144, 24); - this.radioButton2.Name = "radioButton2"; - this.radioButton2.TabIndex = 1; - this.radioButton2.Text = "Visual Basic"; - this.radioButton2.Click += new System.EventHandler(this.radioButton2_CheckedChanged); - // - // radioButton3 - // - this.radioButton3.Location = new System.Drawing.Point(272, 24); - this.radioButton3.Name = "radioButton3"; - this.radioButton3.TabIndex = 2; - this.radioButton3.Text = "JScript"; - this.radioButton3.Click += new System.EventHandler(this.radioButton3_CheckedChanged); - // - // Form1 - // - this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); - this.ClientSize = new System.Drawing.Size(714, 367); - this.Controls.AddRange(new System.Windows.Forms.Control[] { - this.groupBox1, - this.button2, - this.button1, - this.textBox1}); - this.Name = "Form1"; - this.Text = "CodeDOM Samples Framework"; - this.groupBox1.ResumeLayout(false); - this.ResumeLayout(false); - } - #endregion - - [STAThread] - static void Main() - { - Application.Run(new Form1()); - } - - private void ShowCode() - { - this.textBox1.Text=""; - } - - // Show code button - private void button2_Click(object sender, System.EventArgs e) - { - ShowCode(); - } - - // Generate and show code button - private void button1_Click(object sender, System.EventArgs e) - { - OutputGraph(); - } - - // Csharp language selection button - private void radioButton1_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=true; - radioButton2.Checked=false; - radioButton3.Checked=false; - - language=1; - } - - // Visual Basic language selection button - private void radioButton2_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=false; - radioButton2.Checked=true; - radioButton3.Checked=false; - - language=2; - } - - // JScript language selection button - private void radioButton3_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=false; - radioButton2.Checked=false; - radioButton3.Checked=true; - - language=3; - } - } -} -// \ No newline at end of file diff --git a/snippets/csharp/System.CodeDom/CodeAssignStatement/Overview/codeassignstatementsnippet.cs b/snippets/csharp/System.CodeDom/CodeAssignStatement/Overview/codeassignstatementsnippet.cs deleted file mode 100644 index b5a010faacb..00000000000 --- a/snippets/csharp/System.CodeDom/CodeAssignStatement/Overview/codeassignstatementsnippet.cs +++ /dev/null @@ -1,283 +0,0 @@ -// -using System; -using System.CodeDom; -using System.CodeDom.Compiler; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; -using System.Data; -using System.IO; -using Microsoft.CSharp; -using Microsoft.VisualBasic; -using Microsoft.JScript; - -namespace CodeDOMSamples -{ - /// - /// Provides a wrapper for CodeDOM samples. - /// - public class Form1 : System.Windows.Forms.Form - { - private System.CodeDom.CodeCompileUnit cu; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.Button button2; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.RadioButton radioButton1; - private System.Windows.Forms.RadioButton radioButton2; - private System.Windows.Forms.RadioButton radioButton3; - private int language = 1; // 1 = Csharp 2 = VB 3 = JScript - private System.ComponentModel.Container components = null; - - public Form1() - { - InitializeComponent(); - - cu = CreateGraph(); - } - - // - public CodeCompileUnit CreateGraph() - { - // Create a compile unit to contain a CodeDOM graph - CodeCompileUnit cu = new CodeCompileUnit(); - - // Create a namespace named "TestSpace" - CodeNamespace cn = new CodeNamespace("TestSpace"); - - // Create a new type named "TestClass" - CodeTypeDeclaration cd = new CodeTypeDeclaration("TestClass"); - - // Create a new entry point method - CodeEntryPointMethod cm = new CodeEntryPointMethod(); - - // Declare a variable of type Int32 named "i" - CodeVariableDeclarationStatement cv1 = new CodeVariableDeclarationStatement("System.Int32", "i"); - - // Add the variable declaration statement to the entry point method - cm.Statements.Add(cv1); - - // - // Assigns the value of the 10 to the integer variable "i". - CodeAssignStatement as1 = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodePrimitiveExpression(10)); - - // A C# code generator produces the following source code for the preceeding example code: - - // i=10; - // - - // Add the assignment statement to the entry point method - cm.Statements.Add(as1); - - // Add the entry point method to the "TestClass" type - cd.Members.Add(cm); - - // Add the "TestClass" type to the namespace - cn.Types.Add(cd); - - // Add the "TestSpace" namespace to the compile unit - cu.Namespaces.Add(cn); - - return cu; - } - // - - private void OutputGraph() - { - // Create string writer to output to textbox - StringWriter sw = new StringWriter(); - - // Create appropriate CodeProvider - System.CodeDom.Compiler.CodeDomProvider cp; - switch(language) - { - case 2: // VB - cp = CodeDomProvider.CreateProvider("VisualBasic"); - break; - case 3: // JScript - cp = CodeDomProvider.CreateProvider("JScript"); - break; - default: // CSharp - cp = CodeDomProvider.CreateProvider("CSharp"); - break; - } - - // Create a code generator that will output to the string writer - ICodeGenerator cg = cp.CreateGenerator(sw); - - // Generate code from the compile unit and outputs it to the string writer - cg.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions()); - - // Output the contents of the string writer to the textbox - this.textBox1.Text = sw.ToString(); - } - - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - if (components != null) - { - components.Dispose(); - } - } - base.Dispose( disposing ); - } - - #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.textBox1 = new System.Windows.Forms.TextBox(); - this.button1 = new System.Windows.Forms.Button(); - this.button2 = new System.Windows.Forms.Button(); - this.groupBox1 = new System.Windows.Forms.GroupBox(); - this.radioButton1 = new System.Windows.Forms.RadioButton(); - this.radioButton2 = new System.Windows.Forms.RadioButton(); - this.radioButton3 = new System.Windows.Forms.RadioButton(); - this.groupBox1.SuspendLayout(); - this.SuspendLayout(); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(16, 112); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBox1.Size = new System.Drawing.Size(664, 248); - this.textBox1.TabIndex = 0; - this.textBox1.Text = ""; - this.textBox1.WordWrap = false; - // - // button1 - // - this.button1.BackColor = System.Drawing.Color.Aquamarine; - this.button1.Location = new System.Drawing.Point(16, 16); - this.button1.Name = "button1"; - this.button1.TabIndex = 1; - this.button1.Text = "Generate"; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // button2 - // - this.button2.BackColor = System.Drawing.Color.MediumTurquoise; - this.button2.Location = new System.Drawing.Point(112, 16); - this.button2.Name = "button2"; - this.button2.TabIndex = 2; - this.button2.Text = "Show Code"; - this.button2.Click += new System.EventHandler(this.button2_Click); - // - // groupBox1 - // - this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] { - this.radioButton3, - this.radioButton2, - this.radioButton1}); - this.groupBox1.Location = new System.Drawing.Point(16, 48); - this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(384, 56); - this.groupBox1.TabIndex = 3; - this.groupBox1.TabStop = false; - this.groupBox1.Text = "Language selection"; - // - // radioButton1 - // - this.radioButton1.Checked = true; - this.radioButton1.Location = new System.Drawing.Point(16, 24); - this.radioButton1.Name = "radioButton1"; - this.radioButton1.TabIndex = 0; - this.radioButton1.TabStop = true; - this.radioButton1.Text = "CSharp"; - this.radioButton1.Click += new System.EventHandler(this.radioButton1_CheckedChanged); - // - // radioButton2 - // - this.radioButton2.Location = new System.Drawing.Point(144, 24); - this.radioButton2.Name = "radioButton2"; - this.radioButton2.TabIndex = 1; - this.radioButton2.Text = "Visual Basic"; - this.radioButton2.Click += new System.EventHandler(this.radioButton2_CheckedChanged); - // - // radioButton3 - // - this.radioButton3.Location = new System.Drawing.Point(272, 24); - this.radioButton3.Name = "radioButton3"; - this.radioButton3.TabIndex = 2; - this.radioButton3.Text = "JScript"; - this.radioButton3.Click += new System.EventHandler(this.radioButton3_CheckedChanged); - // - // Form1 - // - this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); - this.ClientSize = new System.Drawing.Size(714, 367); - this.Controls.AddRange(new System.Windows.Forms.Control[] { - this.groupBox1, - this.button2, - this.button1, - this.textBox1}); - this.Name = "Form1"; - this.Text = "CodeDOM Samples Framework"; - this.groupBox1.ResumeLayout(false); - this.ResumeLayout(false); - } - #endregion - - [STAThread] - static void Main() - { - Application.Run(new Form1()); - } - - private void ShowCode() - { - this.textBox1.Text=""; - } - - // Show code button - private void button2_Click(object sender, System.EventArgs e) - { - ShowCode(); - } - - // Generate and show code button - private void button1_Click(object sender, System.EventArgs e) - { - OutputGraph(); - } - - // Csharp language selection button - private void radioButton1_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=true; - radioButton2.Checked=false; - radioButton3.Checked=false; - - language=1; - } - - // Visual Basic language selection button - private void radioButton2_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=false; - radioButton2.Checked=true; - radioButton3.Checked=false; - - language=2; - } - - // JScript language selection button - private void radioButton3_CheckedChanged(object sender, System.EventArgs e) - { - radioButton1.Checked=false; - radioButton2.Checked=false; - radioButton3.Checked=true; - - language=3; - } - } -} -// \ No newline at end of file diff --git a/snippets/csharp/System.CodeDom/CodeAttachEventStatement/Overview/codeattacheventstatementexample.cs b/snippets/csharp/System.CodeDom/CodeAttachEventStatement/Overview/codeattacheventstatementexample.cs index 985e1e1cd96..cec06047575 100644 --- a/snippets/csharp/System.CodeDom/CodeAttachEventStatement/Overview/codeattacheventstatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeAttachEventStatement/Overview/codeattacheventstatementexample.cs @@ -1,72 +1,71 @@ // -using System; using System.CodeDom; namespace CodeDomSamples { public class CodeAttachEventStatementExample { - public CodeAttachEventStatementExample() - { - // - // Declares a type to contain the delegate and constructor method. - CodeTypeDeclaration type1 = new CodeTypeDeclaration("AttachEventTest"); + public CodeAttachEventStatementExample() + { + // + // Declares a type to contain the delegate and constructor method. + CodeTypeDeclaration type1 = new CodeTypeDeclaration("AttachEventTest"); - // Declares an event that needs no custom event arguments class. - CodeMemberEvent event1 = new CodeMemberEvent(); - event1.Name = "TestEvent"; - event1.Type = new CodeTypeReference("System.EventHandler"); - // Adds the event to the type members. - type1.Members.Add( event1 ); + // Declares an event that needs no custom event arguments class. + CodeMemberEvent event1 = new CodeMemberEvent(); + event1.Name = "TestEvent"; + event1.Type = new CodeTypeReference("System.EventHandler"); + // Adds the event to the type members. + type1.Members.Add(event1); - // Declares a method that matches the System.EventHandler method signature. - CodeMemberMethod method1 = new CodeMemberMethod(); - method1.Name = "TestMethod"; - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.Object", "sender") ); - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.EventArgs", "e") ); - // Adds the method to the type members. - type1.Members.Add( method1 ); + // Declares a method that matches the System.EventHandler method signature. + CodeMemberMethod method1 = new CodeMemberMethod(); + method1.Name = "TestMethod"; + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); + // Adds the method to the type members. + type1.Members.Add(method1); - // Defines a constructor that attaches a TestDelegate delegate pointing to - // the TestMethod method to the TestEvent event. - CodeConstructor constructor1 = new CodeConstructor(); - constructor1.Attributes = MemberAttributes.Public; + // Defines a constructor that attaches a TestDelegate delegate pointing to + // the TestMethod method to the TestEvent event. + CodeConstructor constructor1 = new CodeConstructor(); + constructor1.Attributes = MemberAttributes.Public; - // - // Defines a delegate creation expression that creates an EventHandler delegate pointing to a method named TestMethod. - CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( - new CodeTypeReference( "System.EventHandler" ), new CodeThisReferenceExpression(), "TestMethod" ); - // Attaches an EventHandler delegate pointing to TestMethod to the TestEvent event. - CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement( new CodeThisReferenceExpression(), "TestEvent", createDelegate1 ); + // + // Defines a delegate creation expression that creates an EventHandler delegate pointing to a method named TestMethod. + CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( + new CodeTypeReference("System.EventHandler"), new CodeThisReferenceExpression(), "TestMethod"); + // Attaches an EventHandler delegate pointing to TestMethod to the TestEvent event. + CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1); - // A C# code generator produces the following source code for the preceeding example code: + // A C# code generator produces the following source code for the preceeding example code: - // this.TestEvent += new System.EventHandler(this.TestMethod); - // + // this.TestEvent += new System.EventHandler(this.TestMethod); + // - // Adds the constructor statements to the construtor. - constructor1.Statements.Add( attachStatement1 ); - // Adds the construtor to the type members. - type1.Members.Add( constructor1 ); + // Adds the constructor statements to the construtor. + constructor1.Statements.Add(attachStatement1); + // Adds the construtor to the type members. + type1.Members.Add(constructor1); - // A C# code generator produces the following source code for the preceeding example code: + // A C# code generator produces the following source code for the preceeding example code: - // public class AttachEventTest - // { - // - // public AttachEventTest() - // { - // this.TestEvent += new System.EventHandler(this.TestMethod); - // } - // - // private event System.EventHandler TestEvent; - // - // private void TestMethod(object sender, System.EventArgs e) - // { - // } - // } - // - } + // public class AttachEventTest + // { + // + // public AttachEventTest() + // { + // this.TestEvent += new System.EventHandler(this.TestMethod); + // } + // + // private event System.EventHandler TestEvent; + // + // private void TestMethod(object sender, System.EventArgs e) + // { + // } + // } + // + } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/source.cs b/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/source.cs index ba24c4fd17e..e82815841dc 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/source.cs +++ b/snippets/csharp/System.CodeDom/CodeAttributeArgument/Overview/source.cs @@ -16,7 +16,7 @@ static void Main() class1.CustomAttributes.Add(codeAttrDecl); CodeAttributeArgument codeAttr = - new CodeAttributeArgument( new CodePrimitiveExpression("This class is obsolete.")); + new CodeAttributeArgument(new CodePrimitiveExpression("This class is obsolete.")); codeAttrDecl = new CodeAttributeDeclaration("System.Obsolete", codeAttr); class1.CustomAttributes.Add(codeAttrDecl); @@ -34,4 +34,4 @@ static void Main() // [System.Obsolete("This class is obsolete.")] // public class Class1 { // } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeAttributeArgumentCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeAttributeArgumentCollection/Overview/class1.cs index bcd9682bba0..89f2506aa21 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeArgumentCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeAttributeArgumentCollection/Overview/class1.cs @@ -1,14 +1,12 @@ -using System; -using System.CodeDom; -using System.CodeDom.Compiler; +using System.CodeDom; namespace CodeAttributeArgumentCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeAttributeArgumentCollection public void CodeAttributeArgumentCollectionExample() @@ -21,20 +19,20 @@ public void CodeAttributeArgumentCollectionExample() // // Adds a CodeAttributeArgument to the collection. - collection.Add( new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true)) ); + collection.Add(new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true))); // // // Adds an array of CodeAttributeArgument objects to the collection. - CodeAttributeArgument[] arguments = { new CodeAttributeArgument(), new CodeAttributeArgument() }; - collection.AddRange( arguments ); + CodeAttributeArgument[] arguments = [new CodeAttributeArgument(), new CodeAttributeArgument()]; + collection.AddRange(arguments); // Adds a collection of CodeAttributeArgument objects to // the collection. CodeAttributeArgumentCollection argumentsCollection = new CodeAttributeArgumentCollection(); - argumentsCollection.Add( new CodeAttributeArgument("TestBooleanArgument", new CodePrimitiveExpression(true)) ); - argumentsCollection.Add( new CodeAttributeArgument("TestIntArgument", new CodePrimitiveExpression(1)) ); - collection.AddRange( argumentsCollection ); + argumentsCollection.Add(new CodeAttributeArgument("TestBooleanArgument", new CodePrimitiveExpression(true))); + argumentsCollection.Add(new CodeAttributeArgument("TestIntArgument", new CodePrimitiveExpression(1))); + collection.AddRange(argumentsCollection); // // @@ -42,15 +40,15 @@ public void CodeAttributeArgumentCollectionExample() // within the collection, and retrieves its index if it is found. CodeAttributeArgument testArgument = new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true)); int itemIndex = -1; - if( collection.Contains( testArgument ) ) - itemIndex = collection.IndexOf( testArgument ); + if (collection.Contains(testArgument)) + itemIndex = collection.IndexOf(testArgument); // // // Copies the contents of the collection beginning at index 0, // to the specified CodeAttributeArgument array. // 'arguments' is a CodeAttributeArgument array. - collection.CopyTo( arguments, 0 ); + collection.CopyTo(arguments, 0); // // @@ -60,13 +58,13 @@ public void CodeAttributeArgumentCollectionExample() // // Inserts a CodeAttributeArgument at index 0 of the collection. - collection.Insert( 0, new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true)) ); + collection.Insert(0, new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true))); // // // Removes the specified CodeAttributeArgument from the collection. CodeAttributeArgument argument = new CodeAttributeArgument("Test Boolean Argument", new CodePrimitiveExpression(true)); - collection.Remove( argument ); + collection.Remove(argument); // // @@ -75,5 +73,5 @@ public void CodeAttributeArgumentCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/source.cs b/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/source.cs index 7fb349abd9b..d8b3d7038ba 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/source.cs +++ b/snippets/csharp/System.CodeDom/CodeAttributeDeclaration/Overview/source.cs @@ -29,4 +29,4 @@ static void Main() // [System.CLSCompliantAttribute(false)] // public class Class1 { // } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeAttributeDeclarationCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeAttributeDeclarationCollection/Overview/class1.cs index 4190486c164..647382d7b8b 100644 --- a/snippets/csharp/System.CodeDom/CodeAttributeDeclarationCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeAttributeDeclarationCollection/Overview/class1.cs @@ -1,15 +1,12 @@ -using System; -using System.CodeDom; -using System.CodeDom.Compiler; -using System.Collections; +using System.CodeDom; namespace CodeAttributeDeclarationCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeAttributeDeclarationCollection public void CodeAttributeDeclarationCollectionExample() @@ -22,37 +19,37 @@ public void CodeAttributeDeclarationCollectionExample() // // Adds a CodeAttributeDeclaration to the collection. - collection.Add( new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description"))) ); + collection.Add(new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description")))); // // // Adds an array of CodeAttributeDeclaration objects // to the collection. - CodeAttributeDeclaration[] declarations = { new CodeAttributeDeclaration(), new CodeAttributeDeclaration() }; - collection.AddRange( declarations ); + CodeAttributeDeclaration[] declarations = [new CodeAttributeDeclaration(), new CodeAttributeDeclaration()]; + collection.AddRange(declarations); // Adds a collection of CodeAttributeDeclaration objects // to the collection. CodeAttributeDeclarationCollection declarationsCollection = new CodeAttributeDeclarationCollection(); - declarationsCollection.Add( new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description"))) ); - declarationsCollection.Add( new CodeAttributeDeclaration("BrowsableAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(true))) ); - collection.AddRange( declarationsCollection ); + declarationsCollection.Add(new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description")))); + declarationsCollection.Add(new CodeAttributeDeclaration("BrowsableAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(true)))); + collection.AddRange(declarationsCollection); // // // Tests for the presence of a CodeAttributeDeclaration in // the collection, and retrieves its index if it is found. - CodeAttributeDeclaration testdeclaration = new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description")) ); + CodeAttributeDeclaration testdeclaration = new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description"))); int itemIndex = -1; - if( collection.Contains( testdeclaration ) ) - itemIndex = collection.IndexOf( testdeclaration ); + if (collection.Contains(testdeclaration)) + itemIndex = collection.IndexOf(testdeclaration); // // // Copies the contents of the collection, beginning at index 0, // to the specified CodeAttributeDeclaration array. // 'declarations' is a CodeAttributeDeclaration array. - collection.CopyTo( declarations, 0 ); + collection.CopyTo(declarations, 0); // // @@ -62,14 +59,14 @@ public void CodeAttributeDeclarationCollectionExample() // // Inserts a CodeAttributeDeclaration at index 0 of the collection. - collection.Insert( 0, new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description"))) ); + collection.Insert(0, new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description")))); // // // Removes the specified CodeAttributeDeclaration from // the collection. - CodeAttributeDeclaration declaration = new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description")) ); - collection.Remove( declaration ); + CodeAttributeDeclaration declaration = new CodeAttributeDeclaration("DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("Test Description"))); + collection.Remove(declaration); // // @@ -78,5 +75,5 @@ public void CodeAttributeDeclarationCollectionExample() // // } - } + } } diff --git a/snippets/csharp/System.CodeDom/CodeBaseReferenceExpression/Overview/codebasereferenceexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeBaseReferenceExpression/Overview/codebasereferenceexpressionexample.cs index a1008931a5d..7f2da2ff724 100644 --- a/snippets/csharp/System.CodeDom/CodeBaseReferenceExpression/Overview/codebasereferenceexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeBaseReferenceExpression/Overview/codebasereferenceexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -31,4 +30,4 @@ public CodeBaseReferenceExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeBinaryOperatorExpression/Overview/codebinaryoperatorexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeBinaryOperatorExpression/Overview/codebinaryoperatorexpressionexample.cs index e1a8ed7cb8a..abf9ca3bc66 100644 --- a/snippets/csharp/System.CodeDom/CodeBinaryOperatorExpression/Overview/codebinaryoperatorexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeBinaryOperatorExpression/Overview/codebinaryoperatorexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -19,7 +18,7 @@ public CodeBinaryOperatorExpressionExample() CodeBinaryOperatorType.Add, // Right operand. - new CodePrimitiveExpression(2) ); + new CodePrimitiveExpression(2)); // A C# code generator produces the following source code for the preceeding example code: @@ -29,4 +28,4 @@ public CodeBinaryOperatorExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeCastExpression/Overview/codecastexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeCastExpression/Overview/codecastexpressionexample.cs index da9a54c9fc7..808ea0836bd 100644 --- a/snippets/csharp/System.CodeDom/CodeCastExpression/Overview/codecastexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeCastExpression/Overview/codecastexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,7 +13,7 @@ public CodeCastExpressionExample() // targetType parameter indicating the target type of the cast. "System.Int64", // The CodeExpression to cast, here an Int32 value of 1000. - new CodePrimitiveExpression(1000) ); + new CodePrimitiveExpression(1000)); // A C# code generator produces the following source code for the preceeding example code: @@ -23,4 +22,4 @@ public CodeCastExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/codetrycatchfinallyexample.cs b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/codetrycatchfinallyexample.cs index 1b722e41765..eb154f61f79 100644 --- a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/codetrycatchfinallyexample.cs +++ b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/codetrycatchfinallyexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -15,32 +14,32 @@ public CodeTryCatchFinallyExample() // Defines a method that throws an exception of type System.ApplicationException. CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "ThrowApplicationException"; - method1.Statements.Add( new CodeThrowExceptionStatement( - new CodeObjectCreateExpression("System.ApplicationException", new CodePrimitiveExpression("Test Application Exception")) ) ); - type1.Members.Add( method1 ); + method1.Statements.Add(new CodeThrowExceptionStatement( + new CodeObjectCreateExpression("System.ApplicationException", new CodePrimitiveExpression("Test Application Exception")))); + type1.Members.Add(method1); // Defines a constructor that calls the ThrowApplicationException method from a try block. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // Defines a try statement that calls the ThrowApplicationException method. CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement(); - try1.TryStatements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "ThrowApplicationException" ) ); - constructor1.Statements.Add( try1 ); + try1.TryStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "ThrowApplicationException")); + constructor1.Statements.Add(try1); // Defines a catch clause for exceptions of type ApplicationException. CodeCatchClause catch1 = new CodeCatchClause("ex", new CodeTypeReference("System.ApplicationException")); - catch1.Statements.Add( new CodeCommentStatement("Handle any System.ApplicationException here.") ); - try1.CatchClauses.Add( catch1 ); + catch1.Statements.Add(new CodeCommentStatement("Handle any System.ApplicationException here.")); + try1.CatchClauses.Add(catch1); // Defines a catch clause for any remaining unhandled exception types. CodeCatchClause catch2 = new CodeCatchClause("ex"); - catch2.Statements.Add( new CodeCommentStatement("Handle any other exception type here.") ); - try1.CatchClauses.Add( catch2 ); + catch2.Statements.Add(new CodeCommentStatement("Handle any other exception type here.")); + try1.CatchClauses.Add(catch2); // Defines a finally block by adding to the FinallyStatements collection. - try1.FinallyStatements.Add( new CodeCommentStatement("Handle any finally block statements.") ); + try1.FinallyStatements.Add(new CodeCommentStatement("Handle any finally block statements.")); // A C# code generator produces the following source code for the preceeding example code: @@ -76,4 +75,4 @@ public CodeTryCatchFinallyExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/source2.cs b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/source2.cs index 2d7761390fe..b82070115b0 100644 --- a/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/source2.cs +++ b/snippets/csharp/System.CodeDom/CodeCatchClause/Overview/source2.cs @@ -1,12 +1,12 @@ -// +// using System; class ArgumentOutOfRangeExample { public static void Main() { - int[] array1 = {0, 0}; - int[] array2 = {0, 0}; + int[] array1 = [0, 0]; + int[] array2 = [0, 0]; try { @@ -14,7 +14,7 @@ public static void Main() } catch (ArgumentOutOfRangeException e) { - Console.WriteLine("Error: {0}", e); + Console.WriteLine($"Error: {e}"); throw; } finally diff --git a/snippets/csharp/System.CodeDom/CodeCatchClauseCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeCatchClauseCollection/Overview/class1.cs index 260208efb86..a6fbcf1d103 100644 --- a/snippets/csharp/System.CodeDom/CodeCatchClauseCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeCatchClauseCollection/Overview/class1.cs @@ -1,14 +1,12 @@ -using System; -using System.CodeDom; -using System.CodeDom.Compiler; +using System.CodeDom; namespace CodeCatchClauseCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeCatchClauseCollection public void CodeCatchClauseCollectionExample() @@ -21,19 +19,19 @@ public void CodeCatchClauseCollectionExample() // // Adds a CodeCatchClause to the collection. - collection.Add( new CodeCatchClause("e") ); + collection.Add(new CodeCatchClause("e")); // // // Adds an array of CodeCatchClause objects to the collection. - CodeCatchClause[] clauses = { new CodeCatchClause(), new CodeCatchClause() }; - collection.AddRange( clauses ); + CodeCatchClause[] clauses = [new CodeCatchClause(), new CodeCatchClause()]; + collection.AddRange(clauses); // Adds a collection of CodeCatchClause objects to the collection. CodeCatchClauseCollection clausesCollection = new CodeCatchClauseCollection(); - clausesCollection.Add( new CodeCatchClause("e", new CodeTypeReference(typeof(System.ArgumentOutOfRangeException))) ); - clausesCollection.Add( new CodeCatchClause("e") ); - collection.AddRange( clausesCollection ); + clausesCollection.Add(new CodeCatchClause("e", new CodeTypeReference(typeof(System.ArgumentOutOfRangeException)))); + clausesCollection.Add(new CodeCatchClause("e")); + collection.AddRange(clausesCollection); // // @@ -41,14 +39,14 @@ public void CodeCatchClauseCollectionExample() // collection, and retrieves its index if it is found. CodeCatchClause testClause = new CodeCatchClause("e"); int itemIndex = -1; - if( collection.Contains( testClause ) ) - itemIndex = collection.IndexOf( testClause ); + if (collection.Contains(testClause)) + itemIndex = collection.IndexOf(testClause); // // // Copies the contents of the collection beginning at index 0 to the specified CodeCatchClause array. // 'clauses' is a CodeCatchClause array. - collection.CopyTo( clauses, 0 ); + collection.CopyTo(clauses, 0); // // @@ -58,13 +56,13 @@ public void CodeCatchClauseCollectionExample() // // Inserts a CodeCatchClause at index 0 of the collection. - collection.Insert( 0, new CodeCatchClause("e") ); + collection.Insert(0, new CodeCatchClause("e")); // // // Removes the specified CodeCatchClause from the collection. CodeCatchClause clause = new CodeCatchClause("e"); - collection.Remove( clause ); + collection.Remove(clause); // // @@ -73,5 +71,5 @@ public void CodeCatchClauseCollectionExample() // // } - } + } } diff --git a/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/Project.csproj index 9efbf5d99fe..cec285dda45 100644 --- a/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/Project.csproj @@ -1,13 +1,13 @@ - Library + Exe net10.0 - - + + diff --git a/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/codedirective.cs b/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/codedirective.cs index 2b79f5adf3a..c51c25770e2 100644 --- a/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/codedirective.cs +++ b/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/codedirective.cs @@ -1,13 +1,15 @@ // +using System; using System.CodeDom; using System.CodeDom.Compiler; -using System.Collections; -using System.Collections.Specialized; using System.IO; -using System.Reflection; +using System.Linq; using System.Text.RegularExpressions; -using System.Globalization; -namespace System.CodeDom +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; + +namespace CodeDomExamples { class CodeDirectiveDemo { @@ -19,122 +21,156 @@ static void Main() } catch (Exception e) { - Console.WriteLine("Unexpected Exception:" + e.ToString()); + Console.WriteLine($"Unexpected Exception: {e}"); } } // Create and compile code containing code directives. static void DemonstrateCodeDirectives(string providerName, string sourceFileName, string assemblyName) { + string tempDirectory = Path.Combine(Path.GetTempPath(), $"CodeDomChecksumPragma_{Guid.NewGuid():N}"); + Directory.CreateDirectory(tempDirectory); - CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); - - Console.WriteLine("Building the CodeDOM graph..."); - - CodeCompileUnit cu = new CodeCompileUnit(); - - CreateGraph(cu); - - StringWriter sw = new StringWriter(); - - Console.WriteLine("Generating code..."); - provider.GenerateCodeFromCompileUnit(cu, sw, null); - - string output = sw.ToString(); - output = Regex.Replace(output, "Runtime Version:[^\r\n]*", - "Runtime Version omitted for demo"); - - Console.WriteLine("Dumping source code..."); - Console.WriteLine(output); - - Console.WriteLine("Writing source code to file..."); - Stream s = File.Open(sourceFileName, FileMode.Create); - StreamWriter t = new StreamWriter(s); - t.Write(output); - t.Close(); - s.Close(); - - CompilerParameters opt = new CompilerParameters(new string[]{ - "System.dll", - "System.Xml.dll", - "System.Windows.Forms.dll", - "System.Data.dll", - "System.Drawing.dll"}); - opt.GenerateExecutable = false; - opt.TreatWarningsAsErrors = true; - opt.IncludeDebugInformation = true; - opt.GenerateInMemory = true; + string sourcePath = Path.Combine(tempDirectory, sourceFileName); + string assemblyPath = Path.Combine(tempDirectory, assemblyName); + EmitResult result = default; - CompilerResults results; - - Console.WriteLine("Compiling with " + providerName); - results = provider.CompileAssemblyFromFile(opt, sourceFileName); - - OutputResults(results); - if (results.NativeCompilerReturnValue != 0) + try { - Console.WriteLine(""); - Console.WriteLine("Compilation failed."); + CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); + + Console.WriteLine("Building the CodeDOM graph..."); + + CodeCompileUnit cu = new(); + + CreateGraph(cu); + + StringWriter sw = new(); + + Console.WriteLine("Generating code..."); + provider.GenerateCodeFromCompileUnit(cu, sw, null); + + string output = sw.ToString(); + output = Regex.Replace(output, "Runtime Version:[^\r\n]*", + "Runtime Version omitted for demo"); + + Console.WriteLine("Dumping source code..."); + Console.WriteLine(output); + + Console.WriteLine("Writing source code to file..."); + File.WriteAllText(sourcePath, output); + + CompilerParameters opt = new([ + "System.dll", + "System.Xml.dll", + "System.Windows.Forms.dll", + "System.Data.dll", + "System.Drawing.dll"]) + { + GenerateExecutable = false, + TreatWarningsAsErrors = true, + IncludeDebugInformation = true, + GenerateInMemory = true + }; + + Console.WriteLine($"Compiling."); + + SyntaxTree[] syntaxTrees = + [ + CSharpSyntaxTree.ParseText(File.ReadAllText(sourcePath)) + ]; + + MetadataReference[] refs = [.. ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"))! + .Split(Path.PathSeparator) + .Select(p => MetadataReference.CreateFromFile(p))]; + + CSharpCompilation compilation = CSharpCompilation.Create( + assemblyName: "GeneratedAssembly", + syntaxTrees: syntaxTrees, + references: refs, + options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + + using FileStream fs = File.Create(assemblyPath); + result = compilation.Emit(fs); + + OutputResults(result); + if (!result.Success) + { + Console.WriteLine(""); + Console.WriteLine("Compilation failed."); + } + else + { + Console.WriteLine(""); + Console.WriteLine("Demo complete."); + } } - else + finally { - Console.WriteLine(""); - Console.WriteLine("Demo complete."); + if (Directory.Exists(tempDirectory)) + { + Directory.Delete(tempDirectory, recursive: true); + } } - File.Delete(sourceFileName); } // This example uses the SHA1 and MD5 algorithms. // Due to collision problems with SHA1 and MD5, Microsoft recommends SHA256 or better. - private static Guid HashMD5 = new Guid(0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99); - private static Guid HashSHA1 = new Guid(0xff1816ec, 0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60); + private static Guid s_hashMD5 = new(0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99); + private static Guid s_hashSHA1 = new(0xff1816ec, 0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60); // Create a CodeDOM graph. - static void CreateGraph( CodeCompileUnit cu) + static void CreateGraph(CodeCompileUnit cu) { // - cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, + cu.StartDirectives.Add(new CodeRegionDirective( + CodeRegionMode.Start, "Compile Unit Region")); // // - cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, + cu.EndDirectives.Add(new CodeRegionDirective( + CodeRegionMode.End, string.Empty)); // - // - CodeChecksumPragma pragma1 = new CodeChecksumPragma(); - // - // - pragma1.FileName = "c:\\temp\\test\\OuterLinePragma.txt"; - // - // - pragma1.ChecksumAlgorithmId = HashMD5; - // - // - pragma1.ChecksumData = new byte[] { 0xAA, 0xAA }; - // + CodeChecksumPragma pragma1 = new() + { + // + FileName = "c:\\temp\\test\\OuterLinePragma.txt", + // + // + ChecksumAlgorithmId = s_hashMD5, + // + // + ChecksumData = [0xAA, 0xAA] + // + }; cu.StartDirectives.Add(pragma1); // - CodeChecksumPragma pragma2 = new CodeChecksumPragma("test.txt", HashSHA1, new byte[] { 0xBB, 0xBB, 0xBB }); + CodeChecksumPragma pragma2 = new("test.txt", s_hashSHA1, [0xBB, 0xBB, 0xBB]); // cu.StartDirectives.Add(pragma2); - CodeNamespace ns = new CodeNamespace("Namespace1"); + CodeNamespace ns = new("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.IO")); cu.Namespaces.Add(ns); ns.Comments.Add(new CodeCommentStatement("Namespace Comment")); - CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1"); + CodeTypeDeclaration cd = new("Class1"); ns.Types.Add(cd); cd.Comments.Add(new CodeCommentStatement("Outer Type Comment")); cd.LinePragma = new CodeLinePragma("c:\\temp\\test\\OuterLinePragma.txt", 300); - CodeMemberMethod method1 = new CodeMemberMethod(); - method1.Name = "Method1"; + CodeMemberMethod method1 = new() + { + Name = "Method1" + }; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; - CodeMemberMethod method2 = new CodeMemberMethod(); - method2.Name = "Method2"; + CodeMemberMethod method2 = new() + { + Name = "Method2" + }; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method2.Comments.Add(new CodeCommentStatement("Method 2 Comment")); @@ -147,42 +183,46 @@ static void CreateGraph( CodeCompileUnit cu) cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); - CodeMemberField field1 = new CodeMemberField(typeof(String), "field1"); + CodeMemberField field1 = new(typeof(string), "field1"); cd.Members.Add(field1); field1.Comments.Add(new CodeCommentStatement("Field 1 Comment")); // - CodeRegionDirective codeRegionDirective1 = new CodeRegionDirective(CodeRegionMode.Start, - "Field Region"); + CodeRegionDirective codeRegionDirective1 = new(CodeRegionMode.Start, "Field Region"); // // field1.StartDirectives.Add(codeRegionDirective1); // - CodeRegionDirective codeRegionDirective2 = new CodeRegionDirective(CodeRegionMode.End, - ""); - // - codeRegionDirective2.RegionMode = CodeRegionMode.End; - // - // - codeRegionDirective2.RegionText = string.Empty; + CodeRegionDirective codeRegionDirective2 = new(CodeRegionMode.End, "") + { + // + RegionMode = CodeRegionMode.End, + // + // + RegionText = string.Empty + }; // // field1.EndDirectives.Add(codeRegionDirective2); // // - CodeSnippetStatement snippet1 = new CodeSnippetStatement(); - snippet1.Value = " Console.WriteLine(field1);"; + CodeSnippetStatement snippet1 = new() + { + Value = " Console.WriteLine(field1);" + }; - CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, ""); - regionStart.RegionText = "Snippet Region"; - regionStart.RegionMode = CodeRegionMode.Start; + CodeRegionDirective regionStart = new(CodeRegionMode.End, "") + { + RegionText = "Snippet Region", + RegionMode = CodeRegionMode.Start + }; snippet1.StartDirectives.Add(regionStart); snippet1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); // // CodeStatement example - CodeConstructor constructor1 = new CodeConstructor(); + CodeConstructor constructor1 = new(); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeStatement codeAssignStatement1 = new CodeAssignStatement( new CodeFieldReferenceExpression( @@ -200,13 +240,12 @@ static void CreateGraph( CodeCompileUnit cu) method2.Statements.Add(snippet1); } - static void OutputResults(CompilerResults results) + static void OutputResults(EmitResult result) { - Console.WriteLine("NativeCompilerReturnValue=" + - results.NativeCompilerReturnValue.ToString()); - foreach (string s in results.Output) + Console.WriteLine("Compiler output:"); + foreach (Diagnostic d in result.Diagnostics) { - Console.WriteLine(s); + Console.WriteLine(d.ToString()); } } } diff --git a/snippets/csharp/System.CodeDom/CodeComment/Overview/codecommentexample.cs b/snippets/csharp/System.CodeDom/CodeComment/Overview/codecommentexample.cs index 3d077014df4..e0bcc14a970 100644 --- a/snippets/csharp/System.CodeDom/CodeComment/Overview/codecommentexample.cs +++ b/snippets/csharp/System.CodeDom/CodeComment/Overview/codecommentexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,11 +13,11 @@ public CodeCommentExample() // The text of the comment. "This comment was generated from a System.CodeDom.CodeComment", // Whether the comment is a comment intended for documentation purposes. - false ); + false); // Create a CodeCommentStatement that contains the comment, in order // to add the comment to a CodeTypeDeclaration Members collection. - CodeCommentStatement commentStatement = new CodeCommentStatement( comment ); + CodeCommentStatement commentStatement = new CodeCommentStatement(comment); // A C# code generator produces the following source code for the preceeding example code: @@ -27,4 +26,4 @@ public CodeCommentExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/Project.csproj b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/Project.csproj index 9efbf5d99fe..78571e6b350 100644 --- a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/Project.csproj @@ -1,11 +1,12 @@ - Library + Exe net10.0 + diff --git a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/program.cs b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/program.cs index 54c00c50957..a4ad7364eb7 100644 --- a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/program.cs +++ b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/program.cs @@ -3,7 +3,10 @@ using System.CodeDom; using System.CodeDom.Compiler; using System.IO; -using System.Text.RegularExpressions; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; namespace BasicCodeDomApp { @@ -11,7 +14,7 @@ class Program { static string providerName = "cs"; static string sourceFileName = "test.cs"; - static void Main(string[] args) + public static void Run(string[] args) { CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); @@ -28,23 +31,32 @@ static void Main(string[] args) // // - CompilerParameters opt = new CompilerParameters(new string[]{ - "System.dll" }); - opt.GenerateExecutable = true; - opt.OutputAssembly = "HelloWorld.exe"; - opt.TreatWarningsAsErrors = true; - opt.IncludeDebugInformation = true; - opt.GenerateInMemory = true; - opt.CompilerOptions = "/doc:HelloWorldDoc.xml"; - - CompilerResults results; - LogMessage("Compiling with " + providerName); - results = provider.CompileAssemblyFromFile(opt, sourceFileName); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(sourceFileName)); + string trustedPlatformAssemblies = + (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); + MetadataReference[] references = trustedPlatformAssemblies + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + "HelloWorld", + [syntaxTree], + references, + new CSharpCompilationOptions( + OutputKind.ConsoleApplication, + optimizationLevel: OptimizationLevel.Debug, + generalDiagnosticOption: ReportDiagnostic.Error)); + + using FileStream assemblyStream = File.Create("HelloWorld.exe"); + using FileStream documentationStream = File.Create("HelloWorldDoc.xml"); + EmitResult result = compilation.Emit( + assemblyStream, + xmlDocumentationStream: documentationStream); // - OutputResults(results); - if (results.NativeCompilerReturnValue != 0) + OutputResults(result); + if (!result.Success) { LogMessage(""); LogMessage("Compilation failed."); @@ -57,6 +69,12 @@ static void Main(string[] args) File.Delete(sourceFileName); } + static void Main(string[] args) + { + Run(args); + CodeDOMSample.Run(); + } + // // Build a Hello World program graph using System.CodeDom types. public static CodeCompileUnit BuildHelloWorldGraph() @@ -138,13 +156,12 @@ static void LogMessage(string text) Console.WriteLine(text); } - static void OutputResults(CompilerResults results) + static void OutputResults(EmitResult result) { - LogMessage("NativeCompilerReturnValue=" + - results.NativeCompilerReturnValue.ToString()); - foreach (string s in results.Output) + LogMessage("NativeCompilerReturnValue=" + (result.Success ? 0 : 1)); + foreach (Diagnostic diagnostic in result.Diagnostics) { - LogMessage(s); + LogMessage(diagnostic.ToString()); } } } diff --git a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/source1.cs b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/source1.cs index c2a55106bb2..9815b5758a9 100644 --- a/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/source1.cs +++ b/snippets/csharp/System.CodeDom/CodeCommentStatement/.ctor/source1.cs @@ -3,18 +3,22 @@ using System.CodeDom; using System.CodeDom.Compiler; using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Microsoft.CSharp; public class CodeDOMSample { - public static void Main() + public static void Run() { string sourceFile; int dotSpot; CodeCompileUnit cu = new CodeCompileUnit(); sourceFile = GenerateCSharpCode(cu); - Console.WriteLine("CS source file: {0}", sourceFile); + Console.WriteLine($"CS source file: {sourceFile}"); dotSpot = sourceFile.IndexOf('.'); CompileCSharpCode(sourceFile, sourceFile.Substring(0, dotSpot) + ".exe"); } @@ -57,53 +61,39 @@ public static string GenerateCSharpCode(CodeCompileUnit compileunit) public static bool CompileCSharpCode(string sourceFile, string exeFile) { - CSharpCodeProvider provider = new CSharpCodeProvider(); - - // Build the parameters for source compilation. - CompilerParameters cp = new CompilerParameters(); - - // Add an assembly reference. - cp.ReferencedAssemblies.Add( "System.dll" ); - - // Generate an executable instead of - // a class library. - cp.GenerateExecutable = true; - - // Set the assembly file name to generate. - cp.OutputAssembly = exeFile; - - // Save the assembly as a physical file. - cp.GenerateInMemory = false; - - // Invoke compilation. - CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); - - if (cr.Errors.Count > 0) + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(sourceFile)); + string trustedPlatformAssemblies = + (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); + MetadataReference[] references = trustedPlatformAssemblies + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + Path.GetFileNameWithoutExtension(exeFile), + [syntaxTree], + references, + new CSharpCompilationOptions(OutputKind.ConsoleApplication)); + + using FileStream assemblyStream = File.Create(exeFile); + EmitResult result = compilation.Emit(assemblyStream); + + if (!result.Success) { // Display compilation errors. - Console.WriteLine("Errors building {0} into {1}", - sourceFile, cr.PathToAssembly); - foreach(CompilerError ce in cr.Errors) + Console.WriteLine($"Errors building {sourceFile} into {exeFile}"); + foreach (Diagnostic diagnostic in result.Diagnostics) { - Console.WriteLine(" {0}", ce.ToString()); + Console.WriteLine($" {diagnostic}"); Console.WriteLine(); } } else { - Console.WriteLine("Source {0} built into {1} successfully.", - sourceFile, cr.PathToAssembly); + Console.WriteLine($"Source {sourceFile} built into {exeFile} successfully."); } // Return the results of compilation. - if (cr.Errors.Count > 0) - { - return false; - } - else - { - return true; - } + return result.Success; } // } diff --git a/snippets/csharp/System.CodeDom/CodeCommentStatementCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeCommentStatementCollection/Overview/class1.cs index c8177c737f2..0a1c515bdae 100644 --- a/snippets/csharp/System.CodeDom/CodeCommentStatementCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeCommentStatementCollection/Overview/class1.cs @@ -1,14 +1,12 @@ -using System; -using System.CodeDom; -using System.CodeDom.Compiler; +using System.CodeDom; namespace CodeCommentStatementCollectionExample -{ - public class Class1 - { - public Class1() - { - } +{ + public class Class1 + { + public Class1() + { + } // CodeCommentStatementCollection public void CodeCommentStatementCollectionExample() @@ -21,19 +19,19 @@ public void CodeCommentStatementCollectionExample() // // Adds a CodeCommentStatement to the collection. - collection.Add( new CodeCommentStatement("Test comment") ); + collection.Add(new CodeCommentStatement("Test comment")); // // // Adds an array of CodeCommentStatement objects to the collection. - CodeCommentStatement[] comments = { new CodeCommentStatement("Test comment"), new CodeCommentStatement("Another test comment") }; - collection.AddRange( comments ); + CodeCommentStatement[] comments = [new CodeCommentStatement("Test comment"), new CodeCommentStatement("Another test comment")]; + collection.AddRange(comments); // Adds a collection of CodeCommentStatement objects to the collection. CodeCommentStatementCollection commentsCollection = new CodeCommentStatementCollection(); - commentsCollection.Add( new CodeCommentStatement("Test comment") ); - commentsCollection.Add( new CodeCommentStatement("Another test comment") ); - collection.AddRange( commentsCollection ); + commentsCollection.Add(new CodeCommentStatement("Test comment")); + commentsCollection.Add(new CodeCommentStatement("Another test comment")); + collection.AddRange(commentsCollection); // // @@ -41,15 +39,15 @@ public void CodeCommentStatementCollectionExample() // collection, and retrieves its index if it is found. CodeCommentStatement testComment = new CodeCommentStatement("Test comment"); int itemIndex = -1; - if( collection.Contains( testComment ) ) - itemIndex = collection.IndexOf( testComment ); + if (collection.Contains(testComment)) + itemIndex = collection.IndexOf(testComment); // // // Copies the contents of the collection, beginning at index 0, // to the specified CodeCommentStatement array. // 'comments' is a CodeCommentStatement array. - collection.CopyTo( comments, 0 ); + collection.CopyTo(comments, 0); // // @@ -59,13 +57,13 @@ public void CodeCommentStatementCollectionExample() // // Inserts a CodeCommentStatement at index 0 of the collection. - collection.Insert( 0, new CodeCommentStatement("Test comment") ); + collection.Insert(0, new CodeCommentStatement("Test comment")); // // // Removes the specified CodeCommentStatement from the collection. CodeCommentStatement comment = new CodeCommentStatement("Test comment"); - collection.Remove( comment ); + collection.Remove(comment); // // @@ -74,5 +72,5 @@ public void CodeCommentStatementCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs b/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs deleted file mode 100644 index 25e7f55ad8f..00000000000 --- a/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs +++ /dev/null @@ -1,298 +0,0 @@ -// -using System; -using System.CodeDom; -using System.CodeDom.Compiler; -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.IO; -using System.Windows.Forms; -using Microsoft.CSharp; -using Microsoft.VisualBasic; -using Microsoft.JScript; - -// This example demonstrates building a Hello World program graph -// using System.CodeDom elements. It calls code generator and -// code compiler methods to build the program using CSharp, VB, or -// JScript. A Windows Forms interface is included. Note: Code -// must be compiled and linked with the Microsoft.JScript assembly. -namespace CodeDOMExample -{ - class CodeDomExample - { - // - // Build a Hello World program graph using - // System.CodeDom types. - public static CodeCompileUnit BuildHelloWorldGraph() - { - // Create a new CodeCompileUnit to contain - // the program graph. - CodeCompileUnit compileUnit = new CodeCompileUnit(); - - // Declare a new namespace called Samples. - CodeNamespace samples = new CodeNamespace("Samples"); - // Add the new namespace to the compile unit. - compileUnit.Namespaces.Add(samples); - - // Add the new namespace import for the System namespace. - samples.Imports.Add(new CodeNamespaceImport("System")); - - // Declare a new type called Class1. - CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1"); - // Add the new type to the namespace type collection. - samples.Types.Add(class1); - - // Declare a new code entry point method. - CodeEntryPointMethod start = new CodeEntryPointMethod(); - - // Create a type reference for the System.Console class. - CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console"); - - // Build a Console.WriteLine statement. - CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( - csSystemConsoleType, "WriteLine", - new CodePrimitiveExpression("Hello World!")); - - // Add the WriteLine call to the statement collection. - start.Statements.Add(cs1); - - // Build another Console.WriteLine statement. - CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression( - csSystemConsoleType, "WriteLine", - new CodePrimitiveExpression("Press the Enter key to continue.")); - - // Add the WriteLine call to the statement collection. - start.Statements.Add(cs2); - - // Build a call to System.Console.ReadLine. - CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression( - csSystemConsoleType, "ReadLine"); - - // Add the ReadLine statement. - start.Statements.Add(csReadLine); - - // Add the code entry point method to - // the Members collection of the type. - class1.Members.Add(start); - - return compileUnit; - } - // - - // - public static void GenerateCode(CodeDomProvider provider, - CodeCompileUnit compileunit) - { - // Build the source file name with the appropriate - // language extension. - String sourceFile; - if (provider.FileExtension[0] == '.') - { - sourceFile = "TestGraph" + provider.FileExtension; - } - else - { - sourceFile = "TestGraph." + provider.FileExtension; - } - - // Create an IndentedTextWriter, constructed with - // a StreamWriter to the source file. - IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), " "); - // Generate source code using the code generator. - provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions()); - // Close the output file. - tw.Close(); - } - // - - // - public static CompilerResults CompileCode(CodeDomProvider provider, - String sourceFile, - String exeFile) - { - // Configure a CompilerParameters that links System.dll - // and produces the specified executable file. - String[] referenceAssemblies = { "System.dll" }; - CompilerParameters cp = new CompilerParameters(referenceAssemblies, - exeFile, false); - // Generate an executable rather than a DLL file. - cp.GenerateExecutable = true; - - // Invoke compilation. - CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); - // Return the results of compilation. - return cr; - } - // - } - - public class CodeDomExampleForm : System.Windows.Forms.Form - { - private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button(); - private System.Windows.Forms.Button compile_button = new System.Windows.Forms.Button(); - private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button(); - private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox(); - private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox(); - private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label(); - - private void generate_button_Click(object sender, System.EventArgs e) - { - CodeDomProvider provider = GetCurrentProvider(); - CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph()); - - // Build the source file name with the appropriate - // language extension. - String sourceFile; - if (provider.FileExtension[0] == '.') - { - sourceFile = "TestGraph" + provider.FileExtension; - } - else - { - sourceFile = "TestGraph." + provider.FileExtension; - } - - // Read in the generated source file and - // display the source text. - StreamReader sr = new StreamReader(sourceFile); - textBox1.Text = sr.ReadToEnd(); - sr.Close(); - } - - private void compile_button_Click(object sender, System.EventArgs e) - { - CodeDomProvider provider = GetCurrentProvider(); - - // Build the source file name with the appropriate - // language extension. - String sourceFile; - if (provider.FileExtension[0] == '.') - { - sourceFile = "TestGraph" + provider.FileExtension; - } - else - { - sourceFile = "TestGraph." + provider.FileExtension; - } - - // Compile the source file into an executable output file. - CompilerResults cr = CodeDomExample.CompileCode(provider, - sourceFile, - "TestGraph.exe"); - - if (cr.Errors.Count > 0) - { - // Display compilation errors. - textBox1.Text = "Errors encountered while building " + - sourceFile + " into " + cr.PathToAssembly + ": \r\n\n"; - foreach (CompilerError ce in cr.Errors) - textBox1.AppendText(ce.ToString() + "\r\n"); - run_button.Enabled = false; - } - else - { - textBox1.Text = "Source " + sourceFile + " built into " + - cr.PathToAssembly + " with no errors."; - run_button.Enabled = true; - } - } - - private void run_button_Click(object sender, - System.EventArgs e) - { - Process.Start("TestGraph.exe"); - } - - private CodeDomProvider GetCurrentProvider() - { - CodeDomProvider provider; - switch ((string)this.comboBox1.SelectedItem) - { - case "CSharp": - provider = CodeDomProvider.CreateProvider("CSharp"); - break; - case "Visual Basic": - provider = CodeDomProvider.CreateProvider("VisualBasic"); - break; - case "JScript": - provider = CodeDomProvider.CreateProvider("JScript"); - break; - default: - provider = CodeDomProvider.CreateProvider("CSharp"); - break; - } - return provider; - } - - public CodeDomExampleForm() - { - this.SuspendLayout(); - // Set properties for label1 - this.label1.Location = new System.Drawing.Point(395, 20); - this.label1.Size = new Size(180, 22); - this.label1.Text = "Select a programming language:"; - // Set properties for comboBox1 - this.comboBox1.Location = new System.Drawing.Point(560, 16); - this.comboBox1.Size = new Size(190, 23); - this.comboBox1.Name = "comboBox1"; - this.comboBox1.Items.AddRange(new string[] { "CSharp", "Visual Basic", "JScript" }); - this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left - | System.Windows.Forms.AnchorStyles.Right - | System.Windows.Forms.AnchorStyles.Top; - this.comboBox1.SelectedIndex = 0; - // Set properties for generate_button. - this.generate_button.Location = new System.Drawing.Point(8, 16); - this.generate_button.Name = "generate_button"; - this.generate_button.Size = new System.Drawing.Size(120, 23); - this.generate_button.Text = "Generate Code"; - this.generate_button.Click += new System.EventHandler(this.generate_button_Click); - // Set properties for compile_button. - this.compile_button.Location = new System.Drawing.Point(136, 16); - this.compile_button.Name = "compile_button"; - this.compile_button.Size = new System.Drawing.Size(120, 23); - this.compile_button.Text = "Compile"; - this.compile_button.Click += new System.EventHandler(this.compile_button_Click); - // Set properties for run_button. - this.run_button.Enabled = false; - this.run_button.Location = new System.Drawing.Point(264, 16); - this.run_button.Name = "run_button"; - this.run_button.Size = new System.Drawing.Size(120, 23); - this.run_button.Text = "Run"; - this.run_button.Click += new System.EventHandler(this.run_button_Click); - // Set properties for textBox1. - this.textBox1.Anchor = (System.Windows.Forms.AnchorStyles.Top - | System.Windows.Forms.AnchorStyles.Bottom - | System.Windows.Forms.AnchorStyles.Left - | System.Windows.Forms.AnchorStyles.Right); - this.textBox1.Location = new System.Drawing.Point(8, 48); - this.textBox1.Multiline = true; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(744, 280); - this.textBox1.Text = ""; - // Set properties for the CodeDomExampleForm. - this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); - this.ClientSize = new System.Drawing.Size(768, 340); - this.MinimumSize = new System.Drawing.Size(750, 340); - this.Controls.AddRange(new System.Windows.Forms.Control[] {this.textBox1, - this.run_button, this.compile_button, this.generate_button, - this.comboBox1, this.label1 }); - this.Name = "CodeDomExampleForm"; - this.Text = "CodeDom Hello World Example"; - this.ResumeLayout(false); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - } - - [STAThread] - static void Main() - { - Application.Run(new CodeDomExampleForm()); - } - } -} -// \ No newline at end of file diff --git a/snippets/csharp/System.CodeDom/CodeConditionStatement/Overview/codeconditionstatementexample.cs b/snippets/csharp/System.CodeDom/CodeConditionStatement/Overview/codeconditionstatementexample.cs index bad2e263ec6..0d20993ebe8 100644 --- a/snippets/csharp/System.CodeDom/CodeConditionStatement/Overview/codeconditionstatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeConditionStatement/Overview/codeconditionstatementexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,22 +13,22 @@ public CodeConditionStatementExample() // The condition to test. new CodeVariableReferenceExpression("boolean"), // The statements to execute if the condition evaluates to true. - new CodeStatement[] { new CodeCommentStatement("If condition is true, execute these statements.") }, + [new CodeCommentStatement("If condition is true, execute these statements.")], // The statements to execute if the condition evalues to false. - new CodeStatement[] { new CodeCommentStatement("Else block. If condition is false, execute these statements.") } ); + [new CodeCommentStatement("Else block. If condition is false, execute these statements.")]); // A C# code generator produces the following source code for the preceeding example code: // if (boolean) // { - // // If condition is true, execute these statements. + // // If condition is true, execute these statements. // } // else { // // Else block. If condition is false, execute these statements. - // } + // } // } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeConstructor/Overview/codeconstructorexample.cs b/snippets/csharp/System.CodeDom/CodeConstructor/Overview/codeconstructorexample.cs index 8c563c12f37..f6409c55711 100644 --- a/snippets/csharp/System.CodeDom/CodeConstructor/Overview/codeconstructorexample.cs +++ b/snippets/csharp/System.CodeDom/CodeConstructor/Overview/codeconstructorexample.cs @@ -1,7 +1,5 @@ // -using System; using System.CodeDom; -using System.Reflection; namespace CodeDomSamples { @@ -18,9 +16,9 @@ public CodeConstructorExample() // Declares a new namespace object and names it. CodeNamespace Samples = new CodeNamespace("Samples"); // Adds the namespace object to the compile unit. - CompileUnit.Namespaces.Add( Samples ); + CompileUnit.Namespaces.Add(Samples); // Adds a new namespace import for the System namespace. - Samples.Imports.Add( new CodeNamespaceImport("System") ); + Samples.Imports.Add(new CodeNamespaceImport("System")); // Declares a new type and names it. CodeTypeDeclaration BaseType = new CodeTypeDeclaration("BaseType"); @@ -37,14 +35,14 @@ public CodeConstructorExample() CodeConstructor stringConstructor = new CodeConstructor(); stringConstructor.Attributes = MemberAttributes.Public; // Declares a parameter of type string named "TestStringParameter". - stringConstructor.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "TestStringParameter") ); + stringConstructor.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "TestStringParameter")); // Adds the constructor to the Members collection of the BaseType. BaseType.Members.Add(stringConstructor); // Declares a type that derives from BaseType and names it. CodeTypeDeclaration DerivedType = new CodeTypeDeclaration("DerivedType"); // The DerivedType class inherits from the BaseType class. - DerivedType.BaseTypes.Add( new CodeTypeReference("BaseType") ); + DerivedType.BaseTypes.Add(new CodeTypeReference("BaseType")); // Adds the new type to the namespace object's type collection. Samples.Types.Add(DerivedType); @@ -52,9 +50,9 @@ public CodeConstructorExample() CodeConstructor baseStringConstructor = new CodeConstructor(); baseStringConstructor.Attributes = MemberAttributes.Public; // Declares a parameter of type string named "TestStringParameter". - baseStringConstructor.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "TestStringParameter") ); + baseStringConstructor.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "TestStringParameter")); // Calls a base class constructor with the TestStringParameter parameter. - baseStringConstructor.BaseConstructorArgs.Add( new CodeVariableReferenceExpression("TestStringParameter") ); + baseStringConstructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("TestStringParameter")); // Adds the constructor to the Members collection of the DerivedType. DerivedType.Members.Add(baseStringConstructor); @@ -62,16 +60,16 @@ public CodeConstructorExample() CodeConstructor overloadConstructor = new CodeConstructor(); overloadConstructor.Attributes = MemberAttributes.Public; // Sets the argument to pass to a base constructor method. - overloadConstructor.ChainedConstructorArgs.Add( new CodePrimitiveExpression("Test") ); + overloadConstructor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("Test")); // Adds the constructor to the Members collection of the DerivedType. DerivedType.Members.Add(overloadConstructor); // Declares a constructor overload that calls the default constructor for the type. CodeConstructor overloadConstructor2 = new CodeConstructor(); overloadConstructor2.Attributes = MemberAttributes.Public; - overloadConstructor2.Parameters.Add( new CodeParameterDeclarationExpression("System.Int32", "TestIntParameter") ); + overloadConstructor2.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "TestIntParameter")); // Sets the argument to pass to a base constructor method. - overloadConstructor2.ChainedConstructorArgs.Add( new CodeSnippetExpression("") ); + overloadConstructor2.ChainedConstructorArgs.Add(new CodeSnippetExpression("")); // Adds the constructor to the Members collection of the DerivedType. DerivedType.Members.Add(overloadConstructor2); @@ -105,4 +103,4 @@ public CodeConstructorExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/Project.csproj index 9efbf5d99fe..78571e6b350 100644 --- a/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/Project.csproj @@ -1,11 +1,12 @@ - Library + Exe net10.0 + diff --git a/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/codedomgenerics.cs b/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/codedomgenerics.cs index aee974e2bf6..1fe24571651 100644 --- a/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/codedomgenerics.cs +++ b/snippets/csharp/System.CodeDom/CodeDefaultValueExpression/Overview/codedomgenerics.cs @@ -1,13 +1,12 @@ // -using System.CodeDom; using System.CodeDom.Compiler; -using System.Collections; -using System.Collections.Specialized; +using System.Collections.Generic; using System.IO; -using System.Reflection; +using System.Linq; using System.Text.RegularExpressions; -using System.Globalization; -using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; namespace System.CodeDom { class CodeDomGenericsDemo @@ -54,24 +53,27 @@ static void CreateGenericsCode(string providerName, string sourceFileName, strin t.Close(); s.Close(); - CompilerParameters opt = new CompilerParameters(new string[]{ - "System.dll", - "System.Xml.dll", - "System.Windows.Forms.dll", - "System.Data.dll", - "System.Drawing.dll"}); - opt.GenerateExecutable = false; - opt.TreatWarningsAsErrors = true; - opt.IncludeDebugInformation = true; - opt.GenerateInMemory = true; - - CompilerResults results; - LogMessage("Compiling with " + providerName); - results = provider.CompileAssemblyFromFile(opt, sourceFileName); - - OutputResults(results); - if (results.NativeCompilerReturnValue != 0) + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(sourceFileName)); + string trustedPlatformAssemblies = + (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); + MetadataReference[] references = trustedPlatformAssemblies + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + Path.GetFileNameWithoutExtension(assemblyName), + [syntaxTree], + references, + new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + optimizationLevel: OptimizationLevel.Debug, + generalDiagnosticOption: ReportDiagnostic.Error)); + using MemoryStream assemblyStream = new MemoryStream(); + EmitResult result = compilation.Emit(assemblyStream); + + OutputResults(result); + if (!result.Success) { LogMessage(""); LogMessage("Compilation failed."); @@ -188,7 +190,7 @@ static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu) new CodeVariableReferenceExpression("dict"), "Count"))); -// + // methodMain.Statements.Add(new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( @@ -199,14 +201,14 @@ static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu) new CodeTypeReference("System.Int32"),}), new CodeExpression[0]))); -// + // string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary>[]).FullName; CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName); methodMain.Statements.Add( new CodeVariableDeclarationStatement(dictionaryType, "dict2", - new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) }))); + new CodeArrayCreateExpression(dictionaryType, [new CodePrimitiveExpression(null)]))); methodMain.Statements.Add(ConsoleWriteLineStatement( new CodePropertyReferenceExpression( @@ -238,13 +240,12 @@ static void LogMessage(string text) Console.WriteLine(text); } - static void OutputResults(CompilerResults results) + static void OutputResults(EmitResult result) { - LogMessage("NativeCompilerReturnValue=" + - results.NativeCompilerReturnValue.ToString()); - foreach (string s in results.Output) + LogMessage("NativeCompilerReturnValue=" + (result.Success ? 0 : 1)); + foreach (Diagnostic diagnostic in result.Diagnostics) { - LogMessage(s); + LogMessage(diagnostic.ToString()); } } } diff --git a/snippets/csharp/System.CodeDom/CodeDelegateInvokeExpression/Overview/codedelegateinvokeexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeDelegateInvokeExpression/Overview/codedelegateinvokeexpressionexample.cs index d11d87aaa3a..fc100b44b2a 100644 --- a/snippets/csharp/System.CodeDom/CodeDelegateInvokeExpression/Overview/codedelegateinvokeexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeDelegateInvokeExpression/Overview/codedelegateinvokeexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -17,42 +16,42 @@ public CodeDelegateInvokeExpressionExample() CodeMemberEvent event1 = new CodeMemberEvent(); event1.Name = "TestEvent"; event1.Type = new CodeTypeReference("DelegateInvokeTest.TestDelegate"); - type1.Members.Add( event1 ); + type1.Members.Add(event1); // Declares a delegate type called TestDelegate with an EventArgs parameter. CodeTypeDelegate delegate1 = new CodeTypeDelegate("TestDelegate"); - delegate1.Parameters.Add( new CodeParameterDeclarationExpression("System.Object", "sender") ); - delegate1.Parameters.Add( new CodeParameterDeclarationExpression("System.EventArgs", "e") ); - type1.Members.Add( delegate1 ); + delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); + delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); + type1.Members.Add(delegate1); // Declares a method that matches the "TestDelegate" method signature. CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "TestMethod"; - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.Object", "sender") ); - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.EventArgs", "e") ); - type1.Members.Add( method1 ); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); + type1.Members.Add(method1); // Defines a constructor that attaches a TestDelegate delegate pointing to the TestMethod method // to the TestEvent event. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - constructor1.Statements.Add( new CodeCommentStatement("Attaches a delegate to the TestEvent event.") ); + constructor1.Statements.Add(new CodeCommentStatement("Attaches a delegate to the TestEvent event.")); // Creates and attaches a delegate to the TestEvent. CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( - new CodeTypeReference( "DelegateInvokeTest.TestDelegate" ), new CodeThisReferenceExpression(), "TestMethod" ); - CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement( new CodeThisReferenceExpression(), "TestEvent", createDelegate1 ); - constructor1.Statements.Add( attachStatement1 ); + new CodeTypeReference("DelegateInvokeTest.TestDelegate"), new CodeThisReferenceExpression(), "TestMethod"); + CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1); + constructor1.Statements.Add(attachStatement1); - constructor1.Statements.Add( new CodeCommentStatement("Invokes the TestEvent event.") ); + constructor1.Statements.Add(new CodeCommentStatement("Invokes the TestEvent event.")); // Invokes the TestEvent. - CodeDelegateInvokeExpression invoke1 = new CodeDelegateInvokeExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"), - new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression("System.EventArgs") } ); - constructor1.Statements.Add( invoke1 ); + CodeDelegateInvokeExpression invoke1 = new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"), + [new CodeThisReferenceExpression(), new CodeObjectCreateExpression("System.EventArgs")]); + constructor1.Statements.Add(invoke1); - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: @@ -82,8 +81,8 @@ public void DelegateInvokeOnlyType() { // // Invokes the delegates for an event named TestEvent, passing a local object reference and a new System.EventArgs. - CodeDelegateInvokeExpression invoke1 = new CodeDelegateInvokeExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"), - new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression("System.EventArgs") } ); + CodeDelegateInvokeExpression invoke1 = new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"), + [new CodeThisReferenceExpression(), new CodeObjectCreateExpression("System.EventArgs")]); // A C# code generator produces the following source code for the preceeding example code: @@ -92,4 +91,4 @@ public void DelegateInvokeOnlyType() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeDirectionExpression/Overview/codemultiexample.cs b/snippets/csharp/System.CodeDom/CodeDirectionExpression/Overview/codemultiexample.cs index c486d60db7e..1077e72cad4 100644 --- a/snippets/csharp/System.CodeDom/CodeDirectionExpression/Overview/codemultiexample.cs +++ b/snippets/csharp/System.CodeDom/CodeDirectionExpression/Overview/codemultiexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -15,7 +14,7 @@ public void CodeEventReferenceExample() { // // Represents a reference to an event. - CodeEventReferenceExpression eventRef1 = new CodeEventReferenceExpression( new CodeThisReferenceExpression(), "TestEvent" ); + CodeEventReferenceExpression eventRef1 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"); // A C# code generator produces the following source code for the preceeding example code: @@ -26,7 +25,7 @@ public void CodeEventReferenceExample() public void CodeIndexerExample() { // - System.CodeDom.CodeIndexerExpression indexerExpression = new CodeIndexerExpression( new CodeThisReferenceExpression(), new CodePrimitiveExpression(1) ); + System.CodeDom.CodeIndexerExpression indexerExpression = new CodeIndexerExpression(new CodeThisReferenceExpression(), new CodePrimitiveExpression(1)); // A C# code generator produces the following source code for the preceeding example code: @@ -38,9 +37,9 @@ public void CodeDirectionExample() { // // Declares a parameter passed by reference using a CodeDirectionExpression. - CodeDirectionExpression param1 = new CodeDirectionExpression(FieldDirection.Ref, new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "TestParameter" )); + CodeDirectionExpression param1 = new CodeDirectionExpression(FieldDirection.Ref, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "TestParameter")); // Invokes a method on this named TestMethod using the direction expression as a parameter. - CodeMethodInvokeExpression methodInvoke1 = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "TestMethod", param1 ); + CodeMethodInvokeExpression methodInvoke1 = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "TestMethod", param1); // A C# code generator produces the following source code for the preceeding example code: @@ -51,7 +50,7 @@ public void CodeDirectionExample() public void CreateExpressionExample() { // - CodeObjectCreateExpression objectCreate1 = new CodeObjectCreateExpression( "System.DateTime", new CodeExpression[] {} ); + CodeObjectCreateExpression objectCreate1 = new CodeObjectCreateExpression("System.DateTime", []); // A C# code generator produces the following source code for the preceeding example code: @@ -60,4 +59,4 @@ public void CreateExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeDirectiveCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeDirectiveCollection/Overview/class1.cs index 779eacb0744..fd0f90260ae 100644 --- a/snippets/csharp/System.CodeDom/CodeDirectiveCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeDirectiveCollection/Overview/class1.cs @@ -1,5 +1,4 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeDirectiveCollectionExample { diff --git a/snippets/csharp/System.CodeDom/CodeEntryPointMethod/Overview/codeentrypointmethodexample.cs b/snippets/csharp/System.CodeDom/CodeEntryPointMethod/Overview/codeentrypointmethodexample.cs index a5c29f68f07..23fd5bd75c9 100644 --- a/snippets/csharp/System.CodeDom/CodeEntryPointMethod/Overview/codeentrypointmethodexample.cs +++ b/snippets/csharp/System.CodeDom/CodeEntryPointMethod/Overview/codeentrypointmethodexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -16,10 +15,10 @@ public static CodeCompileUnit BuildHelloWorldGraph() // Declare a new namespace object and name it CodeNamespace Samples = new CodeNamespace("Samples"); // Add the namespace object to the compile unit - CompileUnit.Namespaces.Add( Samples ); + CompileUnit.Namespaces.Add(Samples); // Add a new namespace import for the System namespace - Samples.Imports.Add( new CodeNamespaceImport("System") ); + Samples.Imports.Add(new CodeNamespaceImport("System")); // Declare a new type object and name it CodeTypeDeclaration Class1 = new CodeTypeDeclaration("Class1"); @@ -33,16 +32,16 @@ public static CodeCompileUnit BuildHelloWorldGraph() // Call the System.Console.WriteLine method new CodeTypeReferenceExpression("System.Console"), "WriteLine", // Pass a primitive string parameter to the WriteLine method - new CodePrimitiveExpression("Hello World!") ); + new CodePrimitiveExpression("Hello World!")); // Add the new method code statement Start.Statements.Add(new CodeExpressionStatement(cs1)); // Add the code entry point method to the type's members collection - Class1.Members.Add( Start ); + Class1.Members.Add(Start); return CompileUnit; // } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeExpressionCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeExpressionCollection/Overview/class1.cs index 6f362f0485b..a4d59d16847 100644 --- a/snippets/csharp/System.CodeDom/CodeExpressionCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeExpressionCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeExpressionCollectionExample -{ - public class Class1 - { - public Class1() - { - } +{ + public class Class1 + { + public Class1() + { + } // CodeExpressionCollection public void CodeExpressionCollectionExample() @@ -20,19 +19,19 @@ public void CodeExpressionCollectionExample() // // Adds a CodeExpression to the collection. - collection.Add( new CodePrimitiveExpression(true) ); + collection.Add(new CodePrimitiveExpression(true)); // // // Adds an array of CodeExpression objects to the collection. - CodeExpression[] expressions = { new CodePrimitiveExpression(true), new CodePrimitiveExpression(true) }; - collection.AddRange( expressions ); + CodeExpression[] expressions = [new CodePrimitiveExpression(true), new CodePrimitiveExpression(true)]; + collection.AddRange(expressions); // Adds a collection of CodeExpression objects to the collection. CodeExpressionCollection expressionsCollection = new CodeExpressionCollection(); - expressionsCollection.Add( new CodePrimitiveExpression(true) ); - expressionsCollection.Add( new CodePrimitiveExpression(true) ); - collection.AddRange( expressionsCollection ); + expressionsCollection.Add(new CodePrimitiveExpression(true)); + expressionsCollection.Add(new CodePrimitiveExpression(true)); + collection.AddRange(expressionsCollection); // // @@ -40,14 +39,14 @@ public void CodeExpressionCollectionExample() // collection, and retrieves its index if it is found. CodeExpression testComment = new CodePrimitiveExpression(true); int itemIndex = -1; - if( collection.Contains( testComment ) ) - itemIndex = collection.IndexOf( testComment ); + if (collection.Contains(testComment)) + itemIndex = collection.IndexOf(testComment); // // // Copies the contents of the collection beginning at index 0 to the specified CodeExpression array. // 'expressions' is a CodeExpression array. - collection.CopyTo( expressions, 0 ); + collection.CopyTo(expressions, 0); // // @@ -57,13 +56,13 @@ public void CodeExpressionCollectionExample() // // Inserts a CodeExpression at index 0 of the collection. - collection.Insert( 0, new CodePrimitiveExpression(true) ); + collection.Insert(0, new CodePrimitiveExpression(true)); // // // Removes the specified CodeExpression from the collection. CodeExpression expression = new CodePrimitiveExpression(true); - collection.Remove( expression ); + collection.Remove(expression); // // @@ -72,5 +71,5 @@ public void CodeExpressionCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeExpressionStatement/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeExpressionStatement/Overview/class1.cs index 3104e7492b8..2d4cdbc5884 100644 --- a/snippets/csharp/System.CodeDom/CodeExpressionStatement/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeExpressionStatement/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeDomSampleBatch { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } public static CodeCompileUnit CreateCompileUnit() { @@ -17,11 +16,11 @@ public static CodeCompileUnit CreateCompileUnit() // Creates a code expression for a CodeExpressionStatement to contain. CodeExpression invokeExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), - "Write", new CodePrimitiveExpression("Example string") ); + "Write", new CodePrimitiveExpression("Example string")); // Creates a statement using a code expression. CodeExpressionStatement expressionStatement; - expressionStatement = new CodeExpressionStatement( invokeExpression ); + expressionStatement = new CodeExpressionStatement(invokeExpression); // A C# code generator produces the following source code for the preceeding example code: @@ -62,7 +61,7 @@ public static CodeCompileUnit CreateSnippetCompileUnit() string literalCode; literalCode = "using System; namespace TestLiteralCode " + "{ public class TestClass { public TestClass() {} } }"; - CodeSnippetCompileUnit csu = new CodeSnippetCompileUnit( literalCode ); + CodeSnippetCompileUnit csu = new CodeSnippetCompileUnit(literalCode); // return csu; } @@ -74,12 +73,12 @@ public void CodeNamespaceImportCollectionExample() // // Creates an empty CodeNamespaceImportCollection. CodeNamespaceImportCollection collection = - new CodeNamespaceImportCollection(); + new CodeNamespaceImportCollection(); // // // Adds a CodeNamespaceImport to the collection. - collection.Add( new CodeNamespaceImport("System") ); + collection.Add(new CodeNamespaceImport("System")); // // @@ -87,7 +86,7 @@ public void CodeNamespaceImportCollectionExample() CodeNamespaceImport[] Imports = { new CodeNamespaceImport("System"), new CodeNamespaceImport("System.Drawing") }; - collection.AddRange( Imports ); + collection.AddRange(Imports); // // @@ -96,5 +95,5 @@ public void CodeNamespaceImportCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeFieldReferenceExpression/Overview/codereferenceexample.cs b/snippets/csharp/System.CodeDom/CodeFieldReferenceExpression/Overview/codereferenceexample.cs index f7fced35678..0c9df770380 100644 --- a/snippets/csharp/System.CodeDom/CodeFieldReferenceExpression/Overview/codereferenceexample.cs +++ b/snippets/csharp/System.CodeDom/CodeFieldReferenceExpression/Overview/codereferenceexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -47,4 +46,4 @@ public void CodeVariableReferenceExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeGotoStatement/Overview/codegotostatementexample.cs b/snippets/csharp/System.CodeDom/CodeGotoStatement/Overview/codegotostatementexample.cs index 3b89cb4e06d..aa8f791ffcc 100644 --- a/snippets/csharp/System.CodeDom/CodeGotoStatement/Overview/codegotostatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeGotoStatement/Overview/codegotostatementexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,19 +13,19 @@ public CodeGotoStatementExample() CodeTypeDeclaration type1 = new CodeTypeDeclaration("Type1"); // Declares an entry point method. CodeEntryPointMethod entry1 = new CodeEntryPointMethod(); - type1.Members.Add( entry1 ); + type1.Members.Add(entry1); // Adds a goto statement to continue program flow at the "JumpToLabel" label. CodeGotoStatement goto1 = new CodeGotoStatement("JumpToLabel"); - entry1.Statements.Add( goto1 ); + entry1.Statements.Add(goto1); // Invokes Console.WriteLine to print "Test Output", which is skipped by the goto statement. CodeMethodInvokeExpression method1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Test Output.")); - entry1.Statements.Add( method1 ); + entry1.Statements.Add(method1); // Declares a label named "JumpToLabel" associated with a method to output a test string using Console.WriteLine. CodeMethodInvokeExpression method2 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Output from labeled statement.")); - CodeLabeledStatement label1 = new CodeLabeledStatement("JumpToLabel", new CodeExpressionStatement(method2) ); - entry1.Statements.Add( label1 ); + CodeLabeledStatement label1 = new CodeLabeledStatement("JumpToLabel", new CodeExpressionStatement(method2)); + entry1.Statements.Add(label1); // A C# code generator produces the following source code for the preceeding example code: @@ -45,4 +44,4 @@ public CodeGotoStatementExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeIterationStatement/Overview/codeiterationstatementexample.cs b/snippets/csharp/System.CodeDom/CodeIterationStatement/Overview/codeiterationstatementexample.cs index c8bfe468d84..94645021060 100644 --- a/snippets/csharp/System.CodeDom/CodeIterationStatement/Overview/codeiterationstatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeIterationStatement/Overview/codeiterationstatementexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -10,23 +9,23 @@ public CodeIterationStatementExample() { // // Declares and initializes an integer variable named testInt. - CodeVariableDeclarationStatement testInt = new CodeVariableDeclarationStatement(typeof(int), "testInt", new CodePrimitiveExpression(0) ); + CodeVariableDeclarationStatement testInt = new CodeVariableDeclarationStatement(typeof(int), "testInt", new CodePrimitiveExpression(0)); // Creates a for loop that sets testInt to 0 and continues incrementing testInt by 1 each loop until testInt is not less than 10. CodeIterationStatement forLoop = new CodeIterationStatement( // initStatement parameter for pre-loop initialization. - new CodeAssignStatement( new CodeVariableReferenceExpression("testInt"), new CodePrimitiveExpression(1) ), + new CodeAssignStatement(new CodeVariableReferenceExpression("testInt"), new CodePrimitiveExpression(1)), // testExpression parameter to test for continuation condition. - new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("testInt"), - CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(10) ), + new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("testInt"), + CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(10)), // incrementStatement parameter indicates statement to execute after each iteration. - new CodeAssignStatement( new CodeVariableReferenceExpression("testInt"), new CodeBinaryOperatorExpression( - new CodeVariableReferenceExpression("testInt"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1) )), + new CodeAssignStatement(new CodeVariableReferenceExpression("testInt"), new CodeBinaryOperatorExpression( + new CodeVariableReferenceExpression("testInt"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))), // statements parameter contains the statements to execute during each interation of the loop. // Each loop iteration the value of the integer is output using the Console.WriteLine method. new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression("Console"), "WriteLine" ), new CodeMethodInvokeExpression( - new CodeVariableReferenceExpression("testInt"), "ToString" ) ) ) } ); + new CodeVariableReferenceExpression("testInt"), "ToString" ) ) ) }); // A C# code generator produces the following source code for the preceeding example code: @@ -37,4 +36,4 @@ public CodeIterationStatementExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMemberEvent/Overview/codemembereventexample.cs b/snippets/csharp/System.CodeDom/CodeMemberEvent/Overview/codemembereventexample.cs index 1935ba56788..b8d4d9c9a05 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberEvent/Overview/codemembereventexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberEvent/Overview/codemembereventexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -26,12 +25,12 @@ public CodeMemberEventExample() // // Adds the event to the type members collection. - type1.Members.Add( event1 ); + type1.Members.Add(event1); // Declares an empty type constructor. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: @@ -49,4 +48,4 @@ public CodeMemberEventExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/Project.csproj b/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/program.cs b/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/program.cs index 8f9dc38a7a4..9b0717a99ec 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/program.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberField/InitExpression/program.cs @@ -1,10 +1,8 @@ // -using System; -using System.Reflection; -using System.IO; using System.CodeDom; using System.CodeDom.Compiler; -using Microsoft.CSharp; +using System.IO; +using System.Reflection; namespace SampleCodeDom { @@ -154,4 +152,4 @@ static void Main() // } // } //} -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMemberField/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeMemberField/Overview/class1.cs index 2a375ae6f44..bc3bc26a7a9 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberField/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberField/Overview/class1.cs @@ -1,19 +1,18 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeMemberField_PublicConst_Example { - public class Class1 - { + public class Class1 + { private static CodeCompileUnit GetCompileUnit() - { + { CodeCompileUnit cu = new CodeCompileUnit(); CodeNamespace nsp = new CodeNamespace("TestNamespace"); - cu.Namespaces.Add( nsp ); + cu.Namespaces.Add(nsp); CodeTypeDeclaration testType = new CodeTypeDeclaration("testType"); - nsp.Types.Add( testType ); + nsp.Types.Add(testType); // // This example demonstrates declaring a public constant type member field. @@ -30,8 +29,8 @@ private static CodeCompileUnit GetCompileUnit() constPublicField.Attributes = (constPublicField.Attributes & ~MemberAttributes.AccessMask & ~MemberAttributes.ScopeMask) | MemberAttributes.Public | MemberAttributes.Const; // - testType.Members.Add( constPublicField ); + testType.Members.Add(constPublicField); return cu; } - } + } } diff --git a/snippets/csharp/System.CodeDom/CodeMemberField/Overview/codememberfieldexample.cs b/snippets/csharp/System.CodeDom/CodeMemberField/Overview/codememberfieldexample.cs index 20c7a89dbae..9cade686ffa 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberField/Overview/codememberfieldexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberField/Overview/codememberfieldexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,12 +13,12 @@ public CodeMemberFieldExample() // Declares a field of type String named testStringField. CodeMemberField field1 = new CodeMemberField("System.String", "TestStringField"); - type1.Members.Add( field1 ); + type1.Members.Add(field1); // Declares an empty type constructor. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: @@ -35,4 +34,4 @@ public CodeMemberFieldExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMemberMethod/Overview/codemembermethodexample.cs b/snippets/csharp/System.CodeDom/CodeMemberMethod/Overview/codemembermethodexample.cs index 622f2adeef6..4b9658e4a14 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberMethod/Overview/codemembermethodexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberMethod/Overview/codemembermethodexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -13,8 +12,8 @@ public CodeMemberMethodExample() CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "ReturnString"; method1.ReturnType = new CodeTypeReference("System.String"); - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "text") ); - method1.Statements.Add( new CodeMethodReturnStatement( new CodeArgumentReferenceExpression("text") ) ); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "text")); + method1.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("text"))); // A C# code generator produces the following source code for the preceeding example code: @@ -26,4 +25,4 @@ public CodeMemberMethodExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMemberProperty/Overview/codememberpropertyexample.cs b/snippets/csharp/System.CodeDom/CodeMemberProperty/Overview/codememberpropertyexample.cs index 1011caf926a..10dbeecc527 100644 --- a/snippets/csharp/System.CodeDom/CodeMemberProperty/Overview/codememberpropertyexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMemberProperty/Overview/codememberpropertyexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,21 +13,21 @@ public CodeMemberPropertyExample() // Declares a field of type String named testStringField. CodeMemberField field1 = new CodeMemberField("System.String", "testStringField"); - type1.Members.Add( field1 ); + type1.Members.Add(field1); // Declares a property of type String named StringProperty. CodeMemberProperty property1 = new CodeMemberProperty(); property1.Name = "StringProperty"; property1.Type = new CodeTypeReference("System.String"); property1.Attributes = MemberAttributes.Public; - property1.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField") ) ); - property1.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"), new CodePropertySetValueReferenceExpression())); + property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"))); + property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"), new CodePropertySetValueReferenceExpression())); type1.Members.Add(property1); // Declares an empty type constructor. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: @@ -65,8 +64,8 @@ public void SpecificExample() property1.Name = "StringProperty"; property1.Type = new CodeTypeReference("System.String"); property1.Attributes = MemberAttributes.Public; - property1.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField") ) ); - property1.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"), new CodePropertySetValueReferenceExpression())); + property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"))); + property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "testStringField"), new CodePropertySetValueReferenceExpression())); // A C# code generator produces the following source code for the preceeding example code: @@ -85,4 +84,4 @@ public void SpecificExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMethodInvokeExpression/Overview/codemethodinvokeexpressionexample.cs b/snippets/csharp/System.CodeDom/CodeMethodInvokeExpression/Overview/codemethodinvokeexpressionexample.cs index 856f6b67c40..112248adf75 100644 --- a/snippets/csharp/System.CodeDom/CodeMethodInvokeExpression/Overview/codemethodinvokeexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMethodInvokeExpression/Overview/codemethodinvokeexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -15,7 +14,7 @@ public CodeMethodInvokeExpressionExample() // methodName indicates the method to invoke. "Dispose", // parameters array contains the parameters for the method. - new CodeExpression[] { new CodePrimitiveExpression(true) } ); + [new CodePrimitiveExpression(true)]); // A C# code generator produces the following source code for the preceeding example code: @@ -24,4 +23,4 @@ public CodeMethodInvokeExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/Project.csproj b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/source.cs b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/source.cs index dccbf73dde1..37ec065931d 100644 --- a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/source.cs +++ b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/.ctor/source.cs @@ -13,7 +13,7 @@ static void Main() // Declares a type constructor that calls a method. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - class1.Members.Add( constructor1 ); + class1.Members.Add(constructor1); // Creates a method reference for dict.Init. CodeMethodReferenceExpression methodRef1 = @@ -25,8 +25,8 @@ static void Main() new CodeTypeReference("System.Int32")}); // Invokes the dict.Init method from the constructor. - CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( methodRef1, new CodeParameterDeclarationExpression[] {} ); - constructor1.Statements.Add( invoke1 ); + CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression(methodRef1, []); + constructor1.Statements.Add(invoke1); // Create a C# code provider CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); @@ -44,4 +44,4 @@ static void Main() // dict.Init(); // } // } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/Overview/codemethodreferenceexample.cs b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/Overview/codemethodreferenceexample.cs index 93b94d50c4f..4cdaba56066 100644 --- a/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/Overview/codemethodreferenceexample.cs +++ b/snippets/csharp/System.CodeDom/CodeMethodReferenceExpression/Overview/codemethodreferenceexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -20,12 +19,12 @@ public CodeMethodReferenceExample() // Declares a type constructor that calls a method. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // Invokes the TestMethod method of the current type object. - CodeMethodReferenceExpression methodRef1 = new CodeMethodReferenceExpression( new CodeThisReferenceExpression(), "TestMethod" ); - CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( methodRef1, new CodeParameterDeclarationExpression[] {} ); - constructor1.Statements.Add( invoke1 ); + CodeMethodReferenceExpression methodRef1 = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "TestMethod"); + CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression(methodRef1, []); + constructor1.Statements.Add(invoke1); // } @@ -33,8 +32,8 @@ public void InvokeExample() { // // Invokes the TestMethod method of the current type object. - CodeMethodReferenceExpression methodRef1 = new CodeMethodReferenceExpression( new CodeThisReferenceExpression(), "TestMethod" ); - CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( methodRef1, new CodeParameterDeclarationExpression[] {} ); + CodeMethodReferenceExpression methodRef1 = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "TestMethod"); + CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression(methodRef1, []); // A C# code generator produces the following source code for the preceeding example code: @@ -44,4 +43,4 @@ public void InvokeExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeNamespace/Overview/codenamespaceexample.cs b/snippets/csharp/System.CodeDom/CodeNamespace/Overview/codenamespaceexample.cs index 6ccac9d96e0..58b4a5ad6e0 100644 --- a/snippets/csharp/System.CodeDom/CodeNamespace/Overview/codenamespaceexample.cs +++ b/snippets/csharp/System.CodeDom/CodeNamespace/Overview/codenamespaceexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -11,7 +10,7 @@ public CodeMemberEventExample() // CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace namespace1 = new CodeNamespace("TestNamespace"); - compileUnit.Namespaces.Add( namespace1 ); + compileUnit.Namespaces.Add(namespace1); // A C# code generator produces the following source code for the preceeding example code: @@ -22,4 +21,4 @@ public CodeMemberEventExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeNamespaceCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeNamespaceCollection/Overview/class1.cs index 51a7eb34a0c..6847182c97f 100644 --- a/snippets/csharp/System.CodeDom/CodeNamespaceCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeNamespaceCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeNamespaceCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeNamespaceCollection public void CodeNamespaceCollectionExample() @@ -20,19 +19,19 @@ public void CodeNamespaceCollectionExample() // // Adds a CodeNamespace to the collection. - collection.Add( new CodeNamespace("TestNamespace") ); + collection.Add(new CodeNamespace("TestNamespace")); // // // Adds an array of CodeNamespace objects to the collection. - CodeNamespace[] namespaces = { new CodeNamespace("TestNamespace1"), new CodeNamespace("TestNamespace2") }; - collection.AddRange( namespaces ); + CodeNamespace[] namespaces = [new CodeNamespace("TestNamespace1"), new CodeNamespace("TestNamespace2")]; + collection.AddRange(namespaces); // Adds a collection of CodeNamespace objects to the collection. CodeNamespaceCollection namespacesCollection = new CodeNamespaceCollection(); - namespacesCollection.Add( new CodeNamespace("TestNamespace1") ); - namespacesCollection.Add( new CodeNamespace("TestNamespace2") ); - collection.AddRange( namespacesCollection ); + namespacesCollection.Add(new CodeNamespace("TestNamespace1")); + namespacesCollection.Add(new CodeNamespace("TestNamespace2")); + collection.AddRange(namespacesCollection); // // @@ -40,15 +39,15 @@ public void CodeNamespaceCollectionExample() // and retrieves its index if it is found. CodeNamespace testNamespace = new CodeNamespace("TestNamespace"); int itemIndex = -1; - if( collection.Contains( testNamespace ) ) - itemIndex = collection.IndexOf( testNamespace ); + if (collection.Contains(testNamespace)) + itemIndex = collection.IndexOf(testNamespace); // // // Copies the contents of the collection beginning at index 0, // to the specified CodeNamespace array. // 'namespaces' is a CodeNamespace array. - collection.CopyTo( namespaces, 0 ); + collection.CopyTo(namespaces, 0); // // @@ -58,13 +57,13 @@ public void CodeNamespaceCollectionExample() // // Inserts a CodeNamespace at index 0 of the collection. - collection.Insert( 0, new CodeNamespace("TestNamespace") ); + collection.Insert(0, new CodeNamespace("TestNamespace")); // // // Removes the specified CodeNamespace from the collection. CodeNamespace namespace_ = new CodeNamespace("TestNamespace"); - collection.Remove( namespace_ ); + collection.Remove(namespace_); // // @@ -73,5 +72,5 @@ public void CodeNamespaceCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeNamespaceImport/Overview/codenamespaceimportexample.cs b/snippets/csharp/System.CodeDom/CodeNamespaceImport/Overview/codenamespaceimportexample.cs index 437065ed40b..235b1ee399e 100644 --- a/snippets/csharp/System.CodeDom/CodeNamespaceImport/Overview/codenamespaceimportexample.cs +++ b/snippets/csharp/System.CodeDom/CodeNamespaceImport/Overview/codenamespaceimportexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -33,4 +32,4 @@ public CodeNamespaceImportExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpression/Overview/codeparameterdeclarationexample.cs b/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpression/Overview/codeparameterdeclarationexample.cs index 24c2188e89e..6348c24dec3 100644 --- a/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpression/Overview/codeparameterdeclarationexample.cs +++ b/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpression/Overview/codeparameterdeclarationexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,7 +13,7 @@ public CodeParameterDeclarationExample() CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // // Declares a method. @@ -42,4 +41,4 @@ public CodeParameterDeclarationExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpressionCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpressionCollection/Overview/class1.cs index 6fc4c2c2cf6..1d0025e6c70 100644 --- a/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpressionCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeParameterDeclarationExpressionCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeParameterDeclarationExpressionCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeParameterDeclarationExpressionCollection public void CodeParameterDeclarationExpressionCollectionExample() @@ -20,21 +19,21 @@ public void CodeParameterDeclarationExpressionCollectionExample() // // Adds a CodeParameterDeclarationExpression to the collection. - collection.Add( new CodeParameterDeclarationExpression(typeof(int), "testIntArgument") ); + collection.Add(new CodeParameterDeclarationExpression(typeof(int), "testIntArgument")); // // // Adds an array of CodeParameterDeclarationExpression objects // to the collection. - CodeParameterDeclarationExpression[] parameters = { new CodeParameterDeclarationExpression(typeof(int), "testIntArgument"), new CodeParameterDeclarationExpression(typeof(bool), "testBoolArgument") }; - collection.AddRange( parameters ); + CodeParameterDeclarationExpression[] parameters = [new CodeParameterDeclarationExpression(typeof(int), "testIntArgument"), new CodeParameterDeclarationExpression(typeof(bool), "testBoolArgument")]; + collection.AddRange(parameters); // Adds a collection of CodeParameterDeclarationExpression objects // to the collection. CodeParameterDeclarationExpressionCollection parametersCollection = new CodeParameterDeclarationExpressionCollection(); - parametersCollection.Add( new CodeParameterDeclarationExpression(typeof(int), "testIntArgument") ); - parametersCollection.Add( new CodeParameterDeclarationExpression(typeof(bool), "testBoolArgument") ); - collection.AddRange( parametersCollection ); + parametersCollection.Add(new CodeParameterDeclarationExpression(typeof(int), "testIntArgument")); + parametersCollection.Add(new CodeParameterDeclarationExpression(typeof(bool), "testBoolArgument")); + collection.AddRange(parametersCollection); // // @@ -42,14 +41,14 @@ public void CodeParameterDeclarationExpressionCollectionExample() // in the collection, and retrieves its index if it is found. CodeParameterDeclarationExpression testParameter = new CodeParameterDeclarationExpression(typeof(int), "testIntArgument"); int itemIndex = -1; - if( collection.Contains( testParameter ) ) - itemIndex = collection.IndexOf( testParameter ); + if (collection.Contains(testParameter)) + itemIndex = collection.IndexOf(testParameter); // // // Copies the contents of the collection beginning at index 0 to the specified CodeParameterDeclarationExpression array. // 'parameters' is a CodeParameterDeclarationExpression array. - collection.CopyTo( parameters, 0 ); + collection.CopyTo(parameters, 0); // // @@ -60,14 +59,14 @@ public void CodeParameterDeclarationExpressionCollectionExample() // // Inserts a CodeParameterDeclarationExpression at index 0 // of the collection. - collection.Insert( 0, new CodeParameterDeclarationExpression(typeof(int), "testIntArgument") ); + collection.Insert(0, new CodeParameterDeclarationExpression(typeof(int), "testIntArgument")); // // // Removes the specified CodeParameterDeclarationExpression // from the collection. CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(typeof(int), "testIntArgument"); - collection.Remove( parameter ); + collection.Remove(parameter); // // @@ -76,5 +75,5 @@ public void CodeParameterDeclarationExpressionCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodePrimitiveExpression/Overview/codeprimitiveexpressionexample.cs b/snippets/csharp/System.CodeDom/CodePrimitiveExpression/Overview/codeprimitiveexpressionexample.cs index 04b731f4c25..5954ae17824 100644 --- a/snippets/csharp/System.CodeDom/CodePrimitiveExpression/Overview/codeprimitiveexpressionexample.cs +++ b/snippets/csharp/System.CodeDom/CodePrimitiveExpression/Overview/codeprimitiveexpressionexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -21,4 +20,4 @@ public CodePrimitiveExpressionExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodePropertySetValueReferenceExpression/Overview/codepropertysetvalueexample.cs b/snippets/csharp/System.CodeDom/CodePropertySetValueReferenceExpression/Overview/codepropertysetvalueexample.cs index f4feb968b3e..b29cfefa63b 100644 --- a/snippets/csharp/System.CodeDom/CodePropertySetValueReferenceExpression/Overview/codepropertysetvalueexample.cs +++ b/snippets/csharp/System.CodeDom/CodePropertySetValueReferenceExpression/Overview/codepropertysetvalueexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -15,21 +14,21 @@ public CodePropertySetValueExample() // Declares a constructor. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; - type1.Members.Add( constructor1 ); + type1.Members.Add(constructor1); // Declares an integer field. CodeMemberField field1 = new CodeMemberField("System.Int32", "integerField"); - type1.Members.Add( field1 ); + type1.Members.Add(field1); // Declares a property. CodeMemberProperty property1 = new CodeMemberProperty(); // Declares a property get statement to return the value of the integer field. - property1.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField") ) ); + property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"))); // Declares a property set statement to set the value to the integer field. // The CodePropertySetValueReferenceExpression represents the value argument passed to the property set statement. - property1.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"), - new CodePropertySetValueReferenceExpression() ) ); - type1.Members.Add( property1 ); + property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"), + new CodePropertySetValueReferenceExpression())); + type1.Members.Add(property1); // A C# code generator produces the following source code for the preceeding example code: @@ -58,4 +57,4 @@ public CodePropertySetValueExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeRemoveEventStatement/Overview/coderemoveeventexample.cs b/snippets/csharp/System.CodeDom/CodeRemoveEventStatement/Overview/coderemoveeventexample.cs index 86183c0e53b..8eb30ba0105 100644 --- a/snippets/csharp/System.CodeDom/CodeRemoveEventStatement/Overview/coderemoveeventexample.cs +++ b/snippets/csharp/System.CodeDom/CodeRemoveEventStatement/Overview/coderemoveeventexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -10,9 +9,9 @@ public CodeRemoveEventExample() { // // Creates a delegate of type System.EventHandler pointing to a method named OnMouseEnter. - CodeDelegateCreateExpression mouseEnterDelegate = new CodeDelegateCreateExpression( new CodeTypeReference("System.EventHandler"), new CodeThisReferenceExpression(), "OnMouseEnter" ); + CodeDelegateCreateExpression mouseEnterDelegate = new CodeDelegateCreateExpression(new CodeTypeReference("System.EventHandler"), new CodeThisReferenceExpression(), "OnMouseEnter"); // Creates a remove event statement that removes the delegate from the TestEvent event. - CodeRemoveEventStatement removeEvent1 = new CodeRemoveEventStatement( new CodeThisReferenceExpression(), "TestEvent", mouseEnterDelegate ); + CodeRemoveEventStatement removeEvent1 = new CodeRemoveEventStatement(new CodeThisReferenceExpression(), "TestEvent", mouseEnterDelegate); // A C# code generator produces the following source code for the preceeding example code: @@ -21,4 +20,4 @@ public CodeRemoveEventExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeStatementCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeStatementCollection/Overview/class1.cs index f9adbf24ed8..ec86371499b 100644 --- a/snippets/csharp/System.CodeDom/CodeStatementCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeStatementCollection/Overview/class1.cs @@ -1,5 +1,4 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeStatementCollectionExample { @@ -20,7 +19,7 @@ public void CodeStatementCollectionSample() // // Adds a CodeStatement to the collection. - collection.Add( new CodeCommentStatement("Test comment statement") ); + collection.Add(new CodeCommentStatement("Test comment statement")); // // @@ -28,24 +27,24 @@ public void CodeStatementCollectionSample() CodeStatement[] statements = { new CodeCommentStatement("Test comment statement"), new CodeCommentStatement("Test comment statement")}; - collection.AddRange( statements ); + collection.AddRange(statements); // Adds a collection of CodeStatement objects to the collection. CodeStatement testStatement = new CodeCommentStatement("Test comment statement"); CodeStatementCollection statementsCollection = new CodeStatementCollection(); - statementsCollection.Add( new CodeCommentStatement("Test comment statement") ); - statementsCollection.Add( new CodeCommentStatement("Test comment statement") ); - statementsCollection.Add( testStatement ); + statementsCollection.Add(new CodeCommentStatement("Test comment statement")); + statementsCollection.Add(new CodeCommentStatement("Test comment statement")); + statementsCollection.Add(testStatement); - collection.AddRange( statementsCollection ); + collection.AddRange(statementsCollection); // // // Tests for the presence of a CodeStatement in the // collection, and retrieves its index if it is found. int itemIndex = -1; - if( collection.Contains( testStatement ) ) - itemIndex = collection.IndexOf( testStatement ); + if (collection.Contains(testStatement)) + itemIndex = collection.IndexOf(testStatement); // @@ -53,7 +52,7 @@ public void CodeStatementCollectionSample() // Copies the contents of the collection beginning at index 0 to the specified CodeStatement array. // 'statements' is a CodeStatement array. CodeStatement[] statementArray = new CodeStatement[collection.Count]; - collection.CopyTo( statementArray, 0 ); + collection.CopyTo(statementArray, 0); // // @@ -63,12 +62,12 @@ public void CodeStatementCollectionSample() // // Inserts a CodeStatement at index 0 of the collection. - collection.Insert( 0, new CodeCommentStatement("Test comment statement") ); + collection.Insert(0, new CodeCommentStatement("Test comment statement")); // // // Removes the specified CodeStatement from the collection. - collection.Remove( testStatement ); + collection.Remove(testStatement); // // @@ -78,4 +77,4 @@ public void CodeStatementCollectionSample() // } } -} \ No newline at end of file +} diff --git a/snippets/csharp/System.CodeDom/CodeThrowExceptionStatement/Overview/codethrowexceptionstatementexample.cs b/snippets/csharp/System.CodeDom/CodeThrowExceptionStatement/Overview/codethrowexceptionstatementexample.cs index 1f6004df617..7c540124e95 100644 --- a/snippets/csharp/System.CodeDom/CodeThrowExceptionStatement/Overview/codethrowexceptionstatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeThrowExceptionStatement/Overview/codethrowexceptionstatementexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -17,7 +16,7 @@ public CodeThrowExceptionStatementExample() // createType parameter inidicates the type of object to create. new CodeTypeReference(typeof(System.Exception)), // parameters parameter indicates the constructor parameters. - new CodeExpression[] {} ) ); + [])); // A C# code generator produces the following source code for the preceeding example code: @@ -26,4 +25,4 @@ public CodeThrowExceptionStatementExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeTypeConstructor/Overview/codetypeconstructorexample.cs b/snippets/csharp/System.CodeDom/CodeTypeConstructor/Overview/codetypeconstructorexample.cs index f624cd43dac..381f39a7931 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeConstructor/Overview/codetypeconstructorexample.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeConstructor/Overview/codetypeconstructorexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -14,7 +13,7 @@ public CodeTypeConstructorExample() // Declares a static constructor. CodeTypeConstructor constructor2 = new CodeTypeConstructor(); // Adds the static constructor to the type. - type1.Members.Add( constructor2 ); + type1.Members.Add(constructor2); // A C# code generator produces the following source code for the preceeding example code: @@ -29,4 +28,4 @@ public CodeTypeConstructorExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/Project.csproj b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/Project.csproj index 9efbf5d99fe..78571e6b350 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/Project.csproj @@ -1,11 +1,12 @@ - Library + Exe net10.0 + diff --git a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/source.cs b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/source.cs index 70ef2fcd926..dd3e5f47b29 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/source.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/IsPartial/source.cs @@ -6,10 +6,12 @@ using System; using System.CodeDom; using System.CodeDom.Compiler; -using System.Collections; -using System.ComponentModel; -using System.IO; using System.Diagnostics; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; namespace CompilerParametersSamples { @@ -467,12 +469,12 @@ public static void DocumentPropertyGraphExpand(ref CodeCompileUnit baseClass.Members.Add(docDateProp); } - public static String GenerateCode(CodeDomProvider provider, + public static string GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit) { // Build the source file name with the language // extension (vb, cs, js). - String sourceFile = ""; + string sourceFile = ""; // Write the source out in the selected language if // the code generator supports partial type declarations. @@ -502,73 +504,75 @@ public static String GenerateCode(CodeDomProvider provider, // public static bool CompileCode(CodeDomProvider provider, - String sourceFile, - String exeFile) + string sourceFile, + string exeFile) { - CompilerParameters cp = new CompilerParameters(); - - // Generate an executable instead of - // a class library. - cp.GenerateExecutable = true; - - // Set the assembly file name to generate. - cp.OutputAssembly = exeFile; - - // Save the assembly as a physical file. - cp.GenerateInMemory = false; - - // Generate debug information. - cp.IncludeDebugInformation = true; - - // Add an assembly reference. - cp.ReferencedAssemblies.Add("System.dll"); - - // Set the warning level at which - // the compiler should abort compilation - // if a warning of this level occurs. - cp.WarningLevel = 3; - - // Set whether to treat all warnings as errors. - cp.TreatWarningsAsErrors = false; - + string mainTypeName = null; if (provider.Supports(GeneratorSupport.EntryPointMethod)) { // Specify the class that contains // the main method of the executable. - cp.MainClass = "DocumentSamples.DocumentProperties"; + mainTypeName = "DocumentSamples.DocumentProperties"; } // Invoke compilation. - CompilerResults cr = provider.CompileAssemblyFromFile(cp, -sourceFile); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(sourceFile)); + string trustedPlatformAssemblies = + (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); + MetadataReference[] references = trustedPlatformAssemblies + .Split(Path.PathSeparator) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + Path.GetFileNameWithoutExtension(exeFile), + [syntaxTree], + references, + new CSharpCompilationOptions( + OutputKind.ConsoleApplication, + optimizationLevel: OptimizationLevel.Debug, + warningLevel: 3, + mainTypeName: mainTypeName)); + + using FileStream assemblyStream = File.Create(exeFile); + EmitResult result = compilation.Emit(assemblyStream); + + if (result.Success) + { + string runtimeConfigFile = + Path.ChangeExtension(exeFile, ".runtimeconfig.json"); + File.WriteAllText( + runtimeConfigFile, + $$""" + { + "runtimeOptions": { + "tfm": "net{{Environment.Version.Major}}.0", + "framework": { + "name": "Microsoft.NETCore.App", + "version": "{{Environment.Version}}" + } + } + } + """); + } - if (cr.Errors.Count > 0) + if (!result.Success) { // Display compilation errors. - Console.WriteLine("Errors building {0} into {1}", - sourceFile, cr.PathToAssembly); - foreach (CompilerError ce in cr.Errors) + Console.WriteLine($"Errors building {sourceFile} into {exeFile}"); + foreach (Diagnostic diagnostic in result.Diagnostics) { - Console.WriteLine(" {0}", ce.ToString()); + Console.WriteLine($" {diagnostic}"); Console.WriteLine(); } } else { - Console.WriteLine("Source {0} built into {1} successfully.", - sourceFile, cr.PathToAssembly); + Console.WriteLine($"Source {sourceFile} built into {exeFile} successfully."); } // Return the results of compilation. - if (cr.Errors.Count > 0) - { - return false; - } - else - { - return true; - } + return result.Success; } // @@ -576,10 +580,10 @@ public static bool CompileCode(CodeDomProvider provider, static void Main() { CodeDomProvider provider = null; - String exeName = "DocProp.exe"; + string exeName = "DocProp.exe"; Console.WriteLine("Enter the source language for DocumentProperties class (cs, vb, etc):"); - String inputLang = Console.ReadLine(); + string inputLang = Console.ReadLine(); Console.WriteLine(); if (CodeDomProvider.IsDefinedLanguage(inputLang)) @@ -597,7 +601,7 @@ static void Main() DocumentPropertyGraphExpand(ref docPropertyUnit); - String sourceFile = GenerateCode(provider, docPropertyUnit); + string sourceFile = GenerateCode(provider, docPropertyUnit); if (!String.IsNullOrEmpty(sourceFile)) { @@ -606,7 +610,7 @@ static void Main() if (CompileCode(provider, sourceFile, exeName)) { Console.WriteLine("Starting DocProp executable."); - Process.Start(exeName); + Process.Start("dotnet", exeName); } } else diff --git a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/Overview/codetypedeclarationexample.cs b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/Overview/codetypedeclarationexample.cs index 91bdd0e3d38..e3dab821414 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeDeclaration/Overview/codetypedeclarationexample.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeDeclaration/Overview/codetypedeclarationexample.cs @@ -1,7 +1,5 @@ // -using System; using System.CodeDom; -using System.Reflection; namespace CodeDomSamples { @@ -17,7 +15,7 @@ public CodeTypeDeclarationExample() // Sets the member attributes for the type to private. newType.Attributes = MemberAttributes.Private; // Sets a base class which the type inherits from. - newType.BaseTypes.Add( "BaseType" ); + newType.BaseTypes.Add("BaseType"); // A C# code generator produces the following source code for the preceeding example code: @@ -28,4 +26,4 @@ public CodeTypeDeclarationExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeTypeDeclarationCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeTypeDeclarationCollection/Overview/class1.cs index ea992843262..c7409f9fba0 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeDeclarationCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeDeclarationCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeTypeDeclarationCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeTypeDeclarationCollection public void CodeTypeDeclarationCollectionExample() @@ -20,20 +19,20 @@ public void CodeTypeDeclarationCollectionExample() // // Adds a CodeTypeDeclaration to the collection. - collection.Add( new CodeTypeDeclaration("TestType") ); + collection.Add(new CodeTypeDeclaration("TestType")); // // // Adds an array of CodeTypeDeclaration objects to the collection. - CodeTypeDeclaration[] declarations = { new CodeTypeDeclaration("TestType1"), new CodeTypeDeclaration("TestType2") }; - collection.AddRange( declarations ); + CodeTypeDeclaration[] declarations = [new CodeTypeDeclaration("TestType1"), new CodeTypeDeclaration("TestType2")]; + collection.AddRange(declarations); // Adds a collection of CodeTypeDeclaration objects to the // collection. CodeTypeDeclarationCollection declarationsCollection = new CodeTypeDeclarationCollection(); - declarationsCollection.Add( new CodeTypeDeclaration("TestType1") ); - declarationsCollection.Add( new CodeTypeDeclaration("TestType2") ); - collection.AddRange( declarationsCollection ); + declarationsCollection.Add(new CodeTypeDeclaration("TestType1")); + declarationsCollection.Add(new CodeTypeDeclaration("TestType2")); + collection.AddRange(declarationsCollection); // // @@ -41,15 +40,15 @@ public void CodeTypeDeclarationCollectionExample() // collection, and retrieves its index if it is found. CodeTypeDeclaration testDeclaration = new CodeTypeDeclaration("TestType"); int itemIndex = -1; - if( collection.Contains( testDeclaration ) ) - itemIndex = collection.IndexOf( testDeclaration ); + if (collection.Contains(testDeclaration)) + itemIndex = collection.IndexOf(testDeclaration); // // // Copies the contents of the collection, beginning at index 0, // to the specified CodeTypeDeclaration array. // 'declarations' is a CodeTypeDeclaration array. - collection.CopyTo( declarations, 0 ); + collection.CopyTo(declarations, 0); // // @@ -59,13 +58,13 @@ public void CodeTypeDeclarationCollectionExample() // // Inserts a CodeTypeDeclaration at index 0 of the collection. - collection.Insert( 0, new CodeTypeDeclaration("TestType") ); + collection.Insert(0, new CodeTypeDeclaration("TestType")); // // // Removes the specified CodeTypeDeclaration from the collection. CodeTypeDeclaration declaration = new CodeTypeDeclaration("TestType"); - collection.Remove( declaration ); + collection.Remove(declaration); // // @@ -74,5 +73,5 @@ public void CodeTypeDeclarationCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeTypeDelegate/Overview/codetypedelegateexample.cs b/snippets/csharp/System.CodeDom/CodeTypeDelegate/Overview/codetypedelegateexample.cs index c284cee5f06..9b851bf279e 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeDelegate/Overview/codetypedelegateexample.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeDelegate/Overview/codetypedelegateexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -17,36 +16,36 @@ public CodeTypeDelegateExample() CodeMemberEvent event1 = new CodeMemberEvent(); event1.Name = "TestEvent"; event1.Type = new CodeTypeReference("DelegateTest.TestDelegate"); - type1.Members.Add( event1 ); + type1.Members.Add(event1); // // Declares a delegate type called TestDelegate with an EventArgs parameter. CodeTypeDelegate delegate1 = new CodeTypeDelegate("TestDelegate"); - delegate1.Parameters.Add( new CodeParameterDeclarationExpression("System.Object", "sender") ); - delegate1.Parameters.Add( new CodeParameterDeclarationExpression("System.EventArgs", "e") ); + delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); + delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); // A C# code generator produces the following source code for the preceeding example code: // public delegate void TestDelegate(object sender, System.EventArgs e); // - type1.Members.Add( delegate1 ); + type1.Members.Add(delegate1); // Declares a method that matches the "TestDelegate" method signature. CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "TestMethod"; - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.Object", "sender") ); - method1.Parameters.Add( new CodeParameterDeclarationExpression("System.EventArgs", "e") ); - type1.Members.Add( method1 ); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); + method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); + type1.Members.Add(method1); // Defines a constructor that attaches a TestDelegate delegate pointing to the TestMethod method // to the TestEvent event. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( - new CodeTypeReference( "DelegateTest.TestDelegate" ), new CodeThisReferenceExpression(), "TestMethod" ); - CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement( new CodeThisReferenceExpression(), "TestEvent", createDelegate1 ); - constructor1.Statements.Add( attachStatement1 ); - type1.Members.Add( constructor1 ); + new CodeTypeReference("DelegateTest.TestDelegate"), new CodeThisReferenceExpression(), "TestMethod"); + CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1); + constructor1.Statements.Add(attachStatement1); + type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: @@ -71,4 +70,4 @@ public CodeTypeDelegateExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeTypeMemberCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeTypeMemberCollection/Overview/class1.cs index 2f9104fd7b6..49ca0bfc88f 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeMemberCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeMemberCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeTypeMemberCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeTypeMemberCollection public void CodeTypeMemberCollectionExample() @@ -20,19 +19,19 @@ public void CodeTypeMemberCollectionExample() // // Adds a CodeTypeMember to the collection. - collection.Add( new CodeMemberField("System.String", "TestStringField") ); + collection.Add(new CodeMemberField("System.String", "TestStringField")); // // // Adds an array of CodeTypeMember objects to the collection. - CodeTypeMember[] members = { new CodeMemberField("System.String", "TestStringField1"), new CodeMemberField("System.String", "TestStringField2") }; - collection.AddRange( members ); + CodeTypeMember[] members = [new CodeMemberField("System.String", "TestStringField1"), new CodeMemberField("System.String", "TestStringField2")]; + collection.AddRange(members); // Adds a collection of CodeTypeMember objects to the collection. CodeTypeMemberCollection membersCollection = new CodeTypeMemberCollection(); - membersCollection.Add( new CodeMemberField("System.String", "TestStringField1") ); - membersCollection.Add( new CodeMemberField("System.String", "TestStringField2") ); - collection.AddRange( membersCollection ); + membersCollection.Add(new CodeMemberField("System.String", "TestStringField1")); + membersCollection.Add(new CodeMemberField("System.String", "TestStringField2")); + collection.AddRange(membersCollection); // // @@ -40,15 +39,15 @@ public void CodeTypeMemberCollectionExample() // and retrieves its index if it is found. CodeTypeMember testMember = new CodeMemberField("System.String", "TestStringField"); int itemIndex = -1; - if( collection.Contains( testMember ) ) - itemIndex = collection.IndexOf( testMember ); + if (collection.Contains(testMember)) + itemIndex = collection.IndexOf(testMember); // // // Copies the contents of the collection, beginning at index 0, // to the specified CodeTypeMember array. // 'members' is a CodeTypeMember array. - collection.CopyTo( members, 0 ); + collection.CopyTo(members, 0); // // @@ -58,13 +57,13 @@ public void CodeTypeMemberCollectionExample() // // Inserts a CodeTypeMember at index 0 of the collection. - collection.Insert( 0, new CodeMemberField("System.String", "TestStringField") ); + collection.Insert(0, new CodeMemberField("System.String", "TestStringField")); // // // Removes the specified CodeTypeMember from the collection. CodeTypeMember member = new CodeMemberField("System.String", "TestStringField"); - collection.Remove( member ); + collection.Remove(member); // // @@ -73,5 +72,5 @@ public void CodeTypeMemberCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/Project.csproj b/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/Project.csproj index 9efbf5d99fe..9268652f383 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/Project.csproj +++ b/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/codetypeofexample.cs b/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/codetypeofexample.cs index 86342074594..e9fbecf7c16 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/codetypeofexample.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeOfExpression/Overview/codetypeofexample.cs @@ -52,4 +52,4 @@ public static void ShowTypeReferenceExpression() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.CodeDom/CodeTypeReferenceCollection/Overview/class1.cs b/snippets/csharp/System.CodeDom/CodeTypeReferenceCollection/Overview/class1.cs index c53cfc6fc2a..82a946adb9d 100644 --- a/snippets/csharp/System.CodeDom/CodeTypeReferenceCollection/Overview/class1.cs +++ b/snippets/csharp/System.CodeDom/CodeTypeReferenceCollection/Overview/class1.cs @@ -1,13 +1,12 @@ -using System; -using System.CodeDom; +using System.CodeDom; namespace CodeTypeReferenceCollectionExample { - public class Class1 - { - public Class1() - { - } + public class Class1 + { + public Class1() + { + } // CodeTypeReferenceCollection public void CodeTypeReferenceCollectionExample() @@ -20,19 +19,19 @@ public void CodeTypeReferenceCollectionExample() // // Adds a CodeTypeReference to the collection. - collection.Add( new CodeTypeReference(typeof(bool)) ); + collection.Add(new CodeTypeReference(typeof(bool))); // // // Adds an array of CodeTypeReference objects to the collection. - CodeTypeReference[] references = { new CodeTypeReference(typeof(bool)), new CodeTypeReference(typeof(bool)) }; - collection.AddRange( references ); + CodeTypeReference[] references = [new CodeTypeReference(typeof(bool)), new CodeTypeReference(typeof(bool))]; + collection.AddRange(references); // Adds a collection of CodeTypeReference objects to the collection. CodeTypeReferenceCollection referencesCollection = new CodeTypeReferenceCollection(); - referencesCollection.Add( new CodeTypeReference(typeof(bool)) ); - referencesCollection.Add( new CodeTypeReference(typeof(bool)) ); - collection.AddRange( referencesCollection ); + referencesCollection.Add(new CodeTypeReference(typeof(bool))); + referencesCollection.Add(new CodeTypeReference(typeof(bool))); + collection.AddRange(referencesCollection); // // @@ -40,15 +39,15 @@ public void CodeTypeReferenceCollectionExample() // collection, and retrieves its index if it is found. CodeTypeReference testReference = new CodeTypeReference(typeof(bool)); int itemIndex = -1; - if( collection.Contains( testReference ) ) - itemIndex = collection.IndexOf( testReference ); + if (collection.Contains(testReference)) + itemIndex = collection.IndexOf(testReference); // // // Copies the contents of the collection, beginning at index 0, // to the specified CodeTypeReference array. // 'references' is a CodeTypeReference array. - collection.CopyTo( references, 0 ); + collection.CopyTo(references, 0); // // @@ -58,13 +57,13 @@ public void CodeTypeReferenceCollectionExample() // // Inserts a CodeTypeReference at index 0 of the collection. - collection.Insert( 0, new CodeTypeReference(typeof(bool)) ); + collection.Insert(0, new CodeTypeReference(typeof(bool))); // // // Removes the specified CodeTypeReference from the collection. CodeTypeReference reference = new CodeTypeReference(typeof(bool)); - collection.Remove( reference ); + collection.Remove(reference); // // @@ -73,5 +72,5 @@ public void CodeTypeReferenceCollectionExample() // // } - } -} \ No newline at end of file + } +} diff --git a/snippets/csharp/System.CodeDom/CodeVariableDeclarationStatement/Overview/codevariabledeclarationstatementexample.cs b/snippets/csharp/System.CodeDom/CodeVariableDeclarationStatement/Overview/codevariabledeclarationstatementexample.cs index d252c7f2ffa..c7a07f39209 100644 --- a/snippets/csharp/System.CodeDom/CodeVariableDeclarationStatement/Overview/codevariabledeclarationstatementexample.cs +++ b/snippets/csharp/System.CodeDom/CodeVariableDeclarationStatement/Overview/codevariabledeclarationstatementexample.cs @@ -1,5 +1,4 @@ // -using System; using System.CodeDom; namespace CodeDomSamples @@ -15,7 +14,7 @@ public CodeVariableDeclarationStatementExample() // Name of the variable to declare. "TestString", // Optional initExpression parameter initializes the variable. - new CodePrimitiveExpression("Testing") ); + new CodePrimitiveExpression("Testing")); // A C# code generator produces the following source code for the preceeding example code: @@ -24,4 +23,4 @@ public CodeVariableDeclarationStatementExample() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/ArrayList/Add/source.cs b/snippets/csharp/System.Collections/ArrayList/Add/source.cs index ef8b2fd7ca3..2b632cb63b6 100644 --- a/snippets/csharp/System.Collections/ArrayList/Add/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Add/source.cs @@ -1,55 +1,61 @@ // - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - - // Creates and initializes a new Queue. - Queue myQueue = new Queue(); - myQueue.Enqueue( "jumps" ); - myQueue.Enqueue( "over" ); - myQueue.Enqueue( "the" ); - myQueue.Enqueue( "lazy" ); - myQueue.Enqueue( "dog" ); - - // Displays the ArrayList and the Queue. - Console.WriteLine( "The ArrayList initially contains the following:" ); - PrintValues( myAL, '\t' ); - Console.WriteLine( "The Queue initially contains the following:" ); - PrintValues( myQueue, '\t' ); - - // Copies the Queue elements to the end of the ArrayList. - myAL.AddRange( myQueue ); - - // Displays the ArrayList. - Console.WriteLine( "The ArrayList now contains the following:" ); - PrintValues( myAL, '\t' ); +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = new(); + myAL.Add("The"); + myAL.Add("quick"); + myAL.Add("brown"); + myAL.Add("fox"); + + // Creates and initializes a new Queue. + Queue myQueue = new(); + myQueue.Enqueue("jumps"); + myQueue.Enqueue("over"); + myQueue.Enqueue("the"); + myQueue.Enqueue("lazy"); + myQueue.Enqueue("dog"); + + // Displays the ArrayList and the Queue. + Console.WriteLine("The ArrayList initially contains the following:"); + PrintValues(myAL, '\t'); + Console.WriteLine("The Queue initially contains the following:"); + PrintValues(myQueue, '\t'); + + // Copies the Queue elements to the end of the ArrayList. + myAL.AddRange(myQueue); + + // Displays the ArrayList. + Console.WriteLine("The ArrayList now contains the following:"); + PrintValues(myAL, '\t'); } - public static void PrintValues( IEnumerable myList, char mySeparator ) { - foreach ( Object obj in myList ) - Console.Write( "{0}{1}", mySeparator, obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, char mySeparator) + { + foreach (object obj in myList) + { + Console.Write($"{mySeparator}{obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The ArrayList initially contains the following: - The quick brown fox - The Queue initially contains the following: - jumps over the lazy dog - The ArrayList now contains the following: - The quick brown fox jumps over the lazy dog - */ +The ArrayList initially contains the following: + The quick brown fox +The Queue initially contains the following: + jumps over the lazy dog +The ArrayList now contains the following: + The quick brown fox jumps over the lazy dog +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/BinarySearch/Program.cs b/snippets/csharp/System.Collections/ArrayList/BinarySearch/Program.cs new file mode 100644 index 00000000000..59623ee2e1f --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/BinarySearch/Program.cs @@ -0,0 +1,2 @@ +SamplesArrayList.Run(); +MyArrayList.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/BinarySearch/Project.csproj b/snippets/csharp/System.Collections/ArrayList/BinarySearch/Project.csproj index be85cf5b17f..45767948950 100644 --- a/snippets/csharp/System.Collections/ArrayList/BinarySearch/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/BinarySearch/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesArrayList diff --git a/snippets/csharp/System.Collections/ArrayList/BinarySearch/source.cs b/snippets/csharp/System.Collections/ArrayList/BinarySearch/source.cs index 1bb8b392cb6..04dcdea1741 100644 --- a/snippets/csharp/System.Collections/ArrayList/BinarySearch/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/BinarySearch/source.cs @@ -1,49 +1,62 @@ -// - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. BinarySearch requires - // a sorted ArrayList. - ArrayList myAL = new ArrayList(); - for ( int i = 0; i <= 4; i++ ) - myAL.Add( i*2 ); - - // Displays the ArrayList. - Console.WriteLine( "The int ArrayList contains the following:" ); - PrintValues( myAL ); - - // Locates a specific object that does not exist in the ArrayList. - Object myObjectOdd = 3; - FindMyObject( myAL, myObjectOdd ); - - // Locates an object that exists in the ArrayList. - Object myObjectEven = 6; - FindMyObject( myAL, myObjectEven ); +// +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Run() + { + + // Creates and initializes a new ArrayList. BinarySearch requires + // a sorted ArrayList. + ArrayList myAL = []; + for (int i = 0; i <= 4; i++) + { + myAL.Add(i * 2); + } + + // Displays the ArrayList. + Console.WriteLine("The int ArrayList contains the following:"); + PrintValues(myAL); + + // Locates a specific object that does not exist in the ArrayList. + object myObjectOdd = 3; + FindMyObject(myAL, myObjectOdd); + + // Locates an object that exists in the ArrayList. + object myObjectEven = 6; + FindMyObject(myAL, myObjectEven); } - public static void FindMyObject( ArrayList myList, Object myObject ) { - int myIndex=myList.BinarySearch( myObject ); - if ( myIndex < 0 ) - Console.WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex ); - else - Console.WriteLine( "The object to search for ({0}) is at index {1}.", myObject, myIndex ); + public static void FindMyObject(ArrayList myList, object myObject) + { + int myIndex = myList.BinarySearch(myObject); + if (myIndex < 0) + { + Console.WriteLine($"The object to search for ({myObject}) is not found. The next larger object is at index {~myIndex}."); + } + else + { + Console.WriteLine($"The object to search for ({myObject}) is at index {myIndex}."); + } } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. - - The int ArrayList contains the following: - 0 2 4 6 8 - The object to search for (3) is not found. The next larger object is at index 2. - The object to search for (6) is at index 3. - */ +} +/* +This code produces the following output. + +The int ArrayList contains the following: + 0 2 4 6 8 +The object to search for (3) is not found. The next larger object is at index 2. +The object to search for (6) is at index 3. +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/BinarySearch/source2.cs b/snippets/csharp/System.Collections/ArrayList/BinarySearch/source2.cs index 9b81139f669..ed08e0173d8 100644 --- a/snippets/csharp/System.Collections/ArrayList/BinarySearch/source2.cs +++ b/snippets/csharp/System.Collections/ArrayList/BinarySearch/source2.cs @@ -13,28 +13,29 @@ int IComparer.Compare(object x, object y) public class MyArrayList : ArrayList { - public static void Main() + public static void Run() { // Creates and initializes a new ArrayList. - MyArrayList coloredAnimals = new MyArrayList(); - - coloredAnimals.Add("White Tiger"); - coloredAnimals.Add("Pink Bunny"); - coloredAnimals.Add("Red Dragon"); - coloredAnimals.Add("Green Frog"); - coloredAnimals.Add("Blue Whale"); - coloredAnimals.Add("Black Cat"); - coloredAnimals.Add("Yellow Lion"); + MyArrayList coloredAnimals = + [ + "White Tiger", + "Pink Bunny", + "Red Dragon", + "Green Frog", + "Blue Whale", + "Black Cat", + "Yellow Lion", + ]; // BinarySearch requires a sorted ArrayList. coloredAnimals.Sort(); - // Compare results of an iterative search with a binary search + // Compare results of an iterative search with a binary search. int index = coloredAnimals.IterativeSearch("White Tiger"); - Console.WriteLine("Iterative search, item found at index: {0}", index); + Console.WriteLine($"Iterative search, item found at index: {index}"); index = coloredAnimals.BinarySearch("White Tiger", new SimpleStringComparer()); - Console.WriteLine("Binary search, item found at index: {0}", index); + Console.WriteLine($"Binary search, item found at index: {index}"); } public int IterativeSearch(object finditem) diff --git a/snippets/csharp/System.Collections/ArrayList/Clear/source.cs b/snippets/csharp/System.Collections/ArrayList/Clear/source.cs index b724cbe7824..581bde2315a 100644 --- a/snippets/csharp/System.Collections/ArrayList/Clear/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Clear/source.cs @@ -1,80 +1,81 @@ // - using System; - using System.Collections; - public class SamplesArrayList { +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); + // Creates and initializes a new ArrayList. + ArrayList myAL = ["The", "quick", "brown", "fox", "jumps"]; - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "Initially," ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("Initially,"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); - // Trim the ArrayList. - myAL.TrimToSize(); + // Trim the ArrayList. + myAL.TrimToSize(); - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "After TrimToSize," ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("After TrimToSize,"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); - // Clear the ArrayList. - myAL.Clear(); + // Clear the ArrayList. + myAL.Clear(); - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "After Clear," ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("After Clear,"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); - // Trim the ArrayList again. - myAL.TrimToSize(); + // Trim the ArrayList again. + myAL.TrimToSize(); - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "After the second TrimToSize," ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("After the second TrimToSize,"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - Initially, - Count : 5 - Capacity : 16 - Values: The quick brown fox jumps - After TrimToSize, - Count : 5 - Capacity : 5 - Values: The quick brown fox jumps - After Clear, - Count : 0 - Capacity : 5 - Values: - After the second TrimToSize, - Count : 0 - Capacity : 16 - Values: - */ +Initially, + Count : 5 + Capacity : 16 + Values: The quick brown fox jumps +After TrimToSize, + Count : 5 + Capacity : 5 + Values: The quick brown fox jumps +After Clear, + Count : 0 + Capacity : 5 + Values: +After the second TrimToSize, + Count : 0 + Capacity : 16 + Values: +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/CopyTo/Program.cs b/snippets/csharp/System.Collections/ArrayList/CopyTo/Program.cs new file mode 100644 index 00000000000..7640237e558 --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/CopyTo/Program.cs @@ -0,0 +1,2 @@ +SamplesArrayList.Run(); +SamplesArrayList1.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/CopyTo/Project.csproj b/snippets/csharp/System.Collections/ArrayList/CopyTo/Project.csproj index be85cf5b17f..45767948950 100644 --- a/snippets/csharp/System.Collections/ArrayList/CopyTo/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/CopyTo/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesArrayList diff --git a/snippets/csharp/System.Collections/ArrayList/CopyTo/source.cs b/snippets/csharp/System.Collections/ArrayList/CopyTo/source.cs index dfec3833252..ee377dbfe1f 100644 --- a/snippets/csharp/System.Collections/ArrayList/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/CopyTo/source.cs @@ -1,70 +1,78 @@ // - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes the source ArrayList. - ArrayList mySourceList = new ArrayList(); - mySourceList.Add( "three" ); - mySourceList.Add( "napping" ); - mySourceList.Add( "cats" ); - mySourceList.Add( "in" ); - mySourceList.Add( "the" ); - mySourceList.Add( "barn" ); - - // Creates and initializes the one-dimensional target Array. - String[] myTargetArray = new String[15]; - myTargetArray[0] = "The"; - myTargetArray[1] = "quick"; - myTargetArray[2] = "brown"; - myTargetArray[3] = "fox"; - myTargetArray[4] = "jumps"; - myTargetArray[5] = "over"; - myTargetArray[6] = "the"; - myTargetArray[7] = "lazy"; - myTargetArray[8] = "dog"; - - // Displays the values of the target Array. - Console.WriteLine( "The target Array contains the following (before and after copying):" ); - PrintValues( myTargetArray, ' ' ); - - // Copies the second element from the source ArrayList to the target Array starting at index 7. - mySourceList.CopyTo( 1, myTargetArray, 7, 1 ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); - - // Copies the entire source ArrayList to the target Array starting at index 6. - mySourceList.CopyTo( myTargetArray, 6 ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); - - // Copies the entire source ArrayList to the target Array starting at index 0. - mySourceList.CopyTo( myTargetArray ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Run() + { + + // Creates and initializes the source ArrayList. + ArrayList mySourceList = + [ + "three", + "napping", + "cats", + "in", + "the", + "barn", + ]; + + // Creates and initializes the one-dimensional target Array. + string[] myTargetArray = new string[15]; + myTargetArray[0] = "The"; + myTargetArray[1] = "quick"; + myTargetArray[2] = "brown"; + myTargetArray[3] = "fox"; + myTargetArray[4] = "jumps"; + myTargetArray[5] = "over"; + myTargetArray[6] = "the"; + myTargetArray[7] = "lazy"; + myTargetArray[8] = "dog"; + + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following (before and after copying):"); + PrintValues(myTargetArray, ' '); + + // Copies the second element from the source ArrayList to the target Array starting at index 7. + mySourceList.CopyTo(1, myTargetArray, 7, 1); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); + + // Copies the entire source ArrayList to the target Array starting at index 6. + mySourceList.CopyTo(myTargetArray, 6); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); + + // Copies the entire source ArrayList to the target Array starting at index 0. + mySourceList.CopyTo(myTargetArray); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); } - public static void PrintValues( String[] myArr, char mySeparator ) { - for ( int i = 0; i < myArr.Length; i++ ) - Console.Write( "{0}{1}", mySeparator, myArr[i] ); - Console.WriteLine(); + public static void PrintValues(string[] myArr, char mySeparator) + { + for (int i = 0; i < myArr.Length; i++) + { + Console.Write($"{mySeparator}{myArr[i]}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The target Array contains the following (before and after copying): - The quick brown fox jumps over the lazy dog - The quick brown fox jumps over the napping dog - The quick brown fox jumps over three napping cats in the barn - three napping cats in the barn three napping cats in the barn - */ +The target Array contains the following (before and after copying): + The quick brown fox jumps over the lazy dog + The quick brown fox jumps over the napping dog + The quick brown fox jumps over three napping cats in the barn + three napping cats in the barn three napping cats in the barn +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/CopyTo/source1.cs b/snippets/csharp/System.Collections/ArrayList/CopyTo/source1.cs index 33ec858056b..2424dbb71dd 100644 --- a/snippets/csharp/System.Collections/ArrayList/CopyTo/source1.cs +++ b/snippets/csharp/System.Collections/ArrayList/CopyTo/source1.cs @@ -1,70 +1,78 @@ // - using System; - using System.Collections; - public class SamplesArrayList1 { - - public static void Main() { - - // Creates and initializes the source ArrayList. - ArrayList mySourceList = new ArrayList(); - mySourceList.Add( "three" ); - mySourceList.Add( "napping" ); - mySourceList.Add( "cats" ); - mySourceList.Add( "in" ); - mySourceList.Add( "the" ); - mySourceList.Add( "barn" ); - - // Creates and initializes the one-dimensional target Array. - String[] myTargetArray = new String[15]; - myTargetArray[0] = "The"; - myTargetArray[1] = "quick"; - myTargetArray[2] = "brown"; - myTargetArray[3] = "fox"; - myTargetArray[4] = "jumps"; - myTargetArray[5] = "over"; - myTargetArray[6] = "the"; - myTargetArray[7] = "lazy"; - myTargetArray[8] = "dog"; - - // Displays the values of the target Array. - Console.WriteLine( "The target Array contains the following (before and after copying):" ); - PrintValues( myTargetArray, ' ' ); - - // Copies the second element from the source ArrayList to the target Array, starting at index 7. - mySourceList.CopyTo( 1, myTargetArray, 7, 1 ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); - - // Copies the entire source ArrayList to the target Array, starting at index 6. - mySourceList.CopyTo( myTargetArray, 6 ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); - - // Copies the entire source ArrayList to the target Array, starting at index 0. - mySourceList.CopyTo( myTargetArray ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); +using System; +using System.Collections; +public class SamplesArrayList1 +{ + + public static void Run() + { + + // Creates and initializes the source ArrayList. + ArrayList mySourceList = + [ + "three", + "napping", + "cats", + "in", + "the", + "barn", + ]; + + // Creates and initializes the one-dimensional target Array. + string[] myTargetArray = new string[15]; + myTargetArray[0] = "The"; + myTargetArray[1] = "quick"; + myTargetArray[2] = "brown"; + myTargetArray[3] = "fox"; + myTargetArray[4] = "jumps"; + myTargetArray[5] = "over"; + myTargetArray[6] = "the"; + myTargetArray[7] = "lazy"; + myTargetArray[8] = "dog"; + + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following (before and after copying):"); + PrintValues(myTargetArray, ' '); + + // Copies the second element from the source ArrayList to the target Array, starting at index 7. + mySourceList.CopyTo(1, myTargetArray, 7, 1); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); + + // Copies the entire source ArrayList to the target Array, starting at index 6. + mySourceList.CopyTo(myTargetArray, 6); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); + + // Copies the entire source ArrayList to the target Array, starting at index 0. + mySourceList.CopyTo(myTargetArray); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); } - public static void PrintValues( String[] myArr, char mySeparator ) { - for ( int i = 0; i < myArr.Length; i++ ) - Console.Write( "{0}{1}", mySeparator, myArr[i] ); - Console.WriteLine(); + public static void PrintValues(string[] myArr, char mySeparator) + { + for (int i = 0; i < myArr.Length; i++) + { + Console.Write($"{mySeparator}{myArr[i]}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The target Array contains the following (before and after copying): - The quick brown fox jumps over the lazy dog - The quick brown fox jumps over the napping dog - The quick brown fox jumps over three napping cats in the barn - three napping cats in the barn three napping cats in the barn +The target Array contains the following (before and after copying): + The quick brown fox jumps over the lazy dog + The quick brown fox jumps over the napping dog + The quick brown fox jumps over three napping cats in the barn + three napping cats in the barn three napping cats in the barn - */ +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/GetEnumerator/Project.csproj b/snippets/csharp/System.Collections/ArrayList/GetEnumerator/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/ArrayList/GetEnumerator/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/GetEnumerator/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/ArrayList/GetEnumerator/program.cs b/snippets/csharp/System.Collections/ArrayList/GetEnumerator/program.cs index 7583784595c..c2cdd79e59d 100644 --- a/snippets/csharp/System.Collections/ArrayList/GetEnumerator/program.cs +++ b/snippets/csharp/System.Collections/ArrayList/GetEnumerator/program.cs @@ -2,36 +2,32 @@ using System; using System.Collections; -class Program -{ - static void Main(string[] args) - { - ArrayList colors = new ArrayList(); - colors.Add("red"); - colors.Add("blue"); - colors.Add("green"); - colors.Add("yellow"); - colors.Add("beige"); - colors.Add("brown"); - colors.Add("magenta"); - colors.Add("purple"); +ArrayList colors = +[ +"red", + "blue", + "green", + "yellow", + "beige", + "brown", + "magenta", + "purple", + ]; - IEnumerator e = colors.GetEnumerator(); - while (e.MoveNext()) - { - Object obj = e.Current; - Console.WriteLine(obj); - } +IEnumerator e = colors.GetEnumerator(); +while (e.MoveNext()) +{ + object obj = e.Current; + Console.WriteLine(obj); +} - Console.WriteLine(); +Console.WriteLine(); - IEnumerator e2 = colors.GetEnumerator(2, 4); - while (e2.MoveNext()) - { - Object obj = e2.Current; - Console.WriteLine(obj); - } - } +IEnumerator e2 = colors.GetEnumerator(2, 4); +while (e2.MoveNext()) +{ + object obj = e2.Current; + Console.WriteLine(obj); } /* This code example produces @@ -50,4 +46,4 @@ static void Main(string[] args) beige brown */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/ArrayList/IndexOf/source.cs b/snippets/csharp/System.Collections/ArrayList/IndexOf/source.cs index e481e9ca9a0..f81a7146c1c 100644 --- a/snippets/csharp/System.Collections/ArrayList/IndexOf/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/IndexOf/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; public class SamplesArrayList @@ -8,47 +8,52 @@ public static void Main() { // Creates and initializes a new ArrayList with three elements of the same value. - ArrayList myAL = new ArrayList(); - myAL.Add( "the" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); - myAL.Add( "in" ); - myAL.Add( "the" ); - myAL.Add( "barn" ); + ArrayList myAL = + [ + "the", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + "in", + "the", + "barn", + ]; // Displays the values of the ArrayList. - Console.WriteLine( "The ArrayList contains the following values:" ); - PrintIndexAndValues( myAL ); + Console.WriteLine("The ArrayList contains the following values:"); + PrintIndexAndValues(myAL); // Search for the first occurrence of the duplicated value. string myString = "the"; - int myIndex = myAL.IndexOf( myString ); - Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex ); + int myIndex = myAL.IndexOf(myString); + Console.WriteLine($"The first occurrence of \"{myString}\" is at index {myIndex}."); // Search for the first occurrence of the duplicated value in the last section of the ArrayList. - myIndex = myAL.IndexOf( myString, 4 ); - Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex ); + myIndex = myAL.IndexOf(myString, 4); + Console.WriteLine($"The first occurrence of \"{myString}\" between index 4 and the end is at index {myIndex}."); // Search for the first occurrence of the duplicated value in a section of the ArrayList. - myIndex = myAL.IndexOf( myString, 6, 6 ); - Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 11 is at index {1}.", myString, myIndex ); + myIndex = myAL.IndexOf(myString, 6, 6); + Console.WriteLine($"The first occurrence of \"{myString}\" between index 6 and index 11 is at index {myIndex}."); // Search for the first occurrence of the duplicated value in a small section at the end of the ArrayList. - myIndex = myAL.IndexOf( myString, 11 ); - Console.WriteLine( "The first occurrence of \"{0}\" between index 11 and the end is at index {1}.", myString, myIndex ); + myIndex = myAL.IndexOf(myString, 11); + Console.WriteLine($"The first occurrence of \"{myString}\" between index 11 and the end is at index {myIndex}."); } public static void PrintIndexAndValues(IEnumerable myList) { int i = 0; - foreach (Object obj in myList) - Console.WriteLine(" [{0}]: {1}", i++, obj); + foreach (object obj in myList) + { + Console.WriteLine($" [{i++}]: {obj}"); + } + Console.WriteLine(); } } diff --git a/snippets/csharp/System.Collections/ArrayList/Insert/source.cs b/snippets/csharp/System.Collections/ArrayList/Insert/source.cs index cd3ef060ec4..4215fbed2ba 100644 --- a/snippets/csharp/System.Collections/ArrayList/Insert/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Insert/source.cs @@ -1,82 +1,91 @@ -// - using System; - using System.Collections; - public class SamplesArrayList { +// +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new ArrayList using Insert instead of Add. - ArrayList myAL = new ArrayList(); - myAL.Insert( 0, "The" ); - myAL.Insert( 1, "fox" ); - myAL.Insert( 2, "jumps" ); - myAL.Insert( 3, "over" ); - myAL.Insert( 4, "the" ); - myAL.Insert( 5, "dog" ); + // Creates and initializes a new ArrayList using Insert instead of Add. + ArrayList myAL = []; + myAL.Insert(0, "The"); + myAL.Insert(1, "fox"); + myAL.Insert(2, "jumps"); + myAL.Insert(3, "over"); + myAL.Insert(4, "the"); + myAL.Insert(5, "dog"); - // Creates and initializes a new Queue. - Queue myQueue = new Queue(); - myQueue.Enqueue( "quick" ); - myQueue.Enqueue( "brown" ); + // Creates and initializes a new Queue. + Queue myQueue = new(); + myQueue.Enqueue("quick"); + myQueue.Enqueue("brown"); - // Displays the ArrayList and the Queue. - Console.WriteLine( "The ArrayList initially contains the following:" ); - PrintValues( myAL ); - Console.WriteLine( "The Queue initially contains the following:" ); - PrintValues( myQueue ); + // Displays the ArrayList and the Queue. + Console.WriteLine("The ArrayList initially contains the following:"); + PrintValues(myAL); + Console.WriteLine("The Queue initially contains the following:"); + PrintValues(myQueue); - // Copies the Queue elements to the ArrayList at index 1. - myAL.InsertRange( 1, myQueue ); + // Copies the Queue elements to the ArrayList at index 1. + myAL.InsertRange(1, myQueue); - // Displays the ArrayList. - Console.WriteLine( "After adding the Queue, the ArrayList now contains:" ); - PrintValues( myAL ); + // Displays the ArrayList. + Console.WriteLine("After adding the Queue, the ArrayList now contains:"); + PrintValues(myAL); - // Search for "dog" and add "lazy" before it. - myAL.Insert( myAL.IndexOf( "dog" ), "lazy" ); + // Search for "dog" and add "lazy" before it. + myAL.Insert(myAL.IndexOf("dog"), "lazy"); - // Displays the ArrayList. - Console.WriteLine( "After adding \"lazy\", the ArrayList now contains:" ); - PrintValues( myAL ); + // Displays the ArrayList. + Console.WriteLine("After adding \"lazy\", the ArrayList now contains:"); + PrintValues(myAL); - // Add "!!!" at the end. - myAL.Insert( myAL.Count, "!!!" ); + // Add "!!!" at the end. + myAL.Insert(myAL.Count, "!!!"); - // Displays the ArrayList. - Console.WriteLine( "After adding \"!!!\", the ArrayList now contains:" ); - PrintValues( myAL ); + // Displays the ArrayList. + Console.WriteLine("After adding \"!!!\", the ArrayList now contains:"); + PrintValues(myAL); - // Inserting an element beyond Count throws an exception. - try { - myAL.Insert( myAL.Count+1, "anystring" ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } + // Inserting an element beyond Count throws an exception. + try + { + myAL.Insert(myAL.Count + 1, "anystring"); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The ArrayList initially contains the following: - The fox jumps over the dog - The Queue initially contains the following: - quick brown - After adding the Queue, the ArrayList now contains: - The quick brown fox jumps over the dog - After adding "lazy", the ArrayList now contains: - The quick brown fox jumps over the lazy dog - After adding "!!!", the ArrayList now contains: - The quick brown fox jumps over the lazy dog !!! - Exception: System.ArgumentOutOfRangeException: Insertion index was out of range. Must be non-negative and less than or equal to size. - Parameter name: index - at System.Collections.ArrayList.Insert(int index, Object value) - at SamplesArrayList.Main() - */ +The ArrayList initially contains the following: + The fox jumps over the dog +The Queue initially contains the following: + quick brown +After adding the Queue, the ArrayList now contains: + The quick brown fox jumps over the dog +After adding "lazy", the ArrayList now contains: + The quick brown fox jumps over the lazy dog +After adding "!!!", the ArrayList now contains: + The quick brown fox jumps over the lazy dog !!! +Exception: System.ArgumentOutOfRangeException: Insertion index was out of range. Must be non-negative and less than or equal to size. +Parameter name: index + at System.Collections.ArrayList.Insert(int index, Object value) + at SamplesArrayList.Main() +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/IsFixedSize/source.cs b/snippets/csharp/System.Collections/ArrayList/IsFixedSize/source.cs index 2d6f3c640f7..baff843ee25 100644 --- a/snippets/csharp/System.Collections/ArrayList/IsFixedSize/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/IsFixedSize/source.cs @@ -1,112 +1,126 @@ -// - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); - - // Create a fixed-size wrapper around the ArrayList. - ArrayList myFixedSizeAL = ArrayList.FixedSize( myAL ); - - // Display whether the ArrayLists have a fixed size or not. - Console.WriteLine( "myAL {0}.", myAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size" ); - Console.WriteLine( "myFixedSizeAL {0}.", myFixedSizeAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size" ); - Console.WriteLine(); - - // Display both ArrayLists. - Console.WriteLine( "Initially," ); - Console.Write( "Standard :" ); - PrintValues( myAL, ' ' ); - Console.Write( "Fixed size:" ); - PrintValues( myFixedSizeAL, ' ' ); - - // Sort is allowed in the fixed-size ArrayList. - myFixedSizeAL.Sort(); - - // Display both ArrayLists. - Console.WriteLine( "After Sort," ); - Console.Write( "Standard :" ); - PrintValues( myAL, ' ' ); - Console.Write( "Fixed size:" ); - PrintValues( myFixedSizeAL, ' ' ); - - // Reverse is allowed in the fixed-size ArrayList. - myFixedSizeAL.Reverse(); - - // Display both ArrayLists. - Console.WriteLine( "After Reverse," ); - Console.Write( "Standard :" ); - PrintValues( myAL, ' ' ); - Console.Write( "Fixed size:" ); - PrintValues( myFixedSizeAL, ' ' ); - - // Add an element to the standard ArrayList. - myAL.Add( "AddMe" ); - - // Display both ArrayLists. - Console.WriteLine( "After adding to the standard ArrayList," ); - Console.Write( "Standard :" ); - PrintValues( myAL, ' ' ); - Console.Write( "Fixed size:" ); - PrintValues( myFixedSizeAL, ' ' ); - Console.WriteLine(); - - // Adding or inserting elements to the fixed-size ArrayList throws an exception. - try { - myFixedSizeAL.Add( "AddMe2" ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } - try { - myFixedSizeAL.Insert( 3, "InsertMe" ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } +// +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; + + // Create a fixed-size wrapper around the ArrayList. + ArrayList myFixedSizeAL = ArrayList.FixedSize(myAL); + + // Display whether the ArrayLists have a fixed size or not. + Console.WriteLine($"myAL {(myAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size")}."); + Console.WriteLine($"myFixedSizeAL {(myFixedSizeAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size")}."); + Console.WriteLine(); + + // Display both ArrayLists. + Console.WriteLine("Initially,"); + Console.Write("Standard :"); + PrintValues(myAL, ' '); + Console.Write("Fixed size:"); + PrintValues(myFixedSizeAL, ' '); + + // Sort is allowed in the fixed-size ArrayList. + myFixedSizeAL.Sort(); + + // Display both ArrayLists. + Console.WriteLine("After Sort,"); + Console.Write("Standard :"); + PrintValues(myAL, ' '); + Console.Write("Fixed size:"); + PrintValues(myFixedSizeAL, ' '); + + // Reverse is allowed in the fixed-size ArrayList. + myFixedSizeAL.Reverse(); + + // Display both ArrayLists. + Console.WriteLine("After Reverse,"); + Console.Write("Standard :"); + PrintValues(myAL, ' '); + Console.Write("Fixed size:"); + PrintValues(myFixedSizeAL, ' '); + + // Add an element to the standard ArrayList. + myAL.Add("AddMe"); + + // Display both ArrayLists. + Console.WriteLine("After adding to the standard ArrayList,"); + Console.Write("Standard :"); + PrintValues(myAL, ' '); + Console.Write("Fixed size:"); + PrintValues(myFixedSizeAL, ' '); + Console.WriteLine(); + + // Adding or inserting elements to the fixed-size ArrayList throws an exception. + try + { + myFixedSizeAL.Add("AddMe2"); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } + try + { + myFixedSizeAL.Insert(3, "InsertMe"); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myList, char mySeparator ) { - foreach ( Object obj in myList ) - Console.Write( "{0}{1}", mySeparator, obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, char mySeparator) + { + foreach (object obj in myList) + { + Console.Write($"{mySeparator}{obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. - - myAL does not have a fixed size. - myFixedSizeAL has a fixed size. - - Initially, - Standard : The quick brown fox jumps over the lazy dog - Fixed size: The quick brown fox jumps over the lazy dog - After Sort, - Standard : brown dog fox jumps lazy over quick the The - Fixed size: brown dog fox jumps lazy over quick the The - After Reverse, - Standard : The the quick over lazy jumps fox dog brown - Fixed size: The the quick over lazy jumps fox dog brown - After adding to the standard ArrayList, - Standard : The the quick over lazy jumps fox dog brown AddMe - Fixed size: The the quick over lazy jumps fox dog brown AddMe - - Exception: System.NotSupportedException: Collection was of a fixed size. - at System.Collections.FixedSizeArrayList.Add(Object obj) - at SamplesArrayList.Main() - Exception: System.NotSupportedException: Collection was of a fixed size. - at System.Collections.FixedSizeArrayList.Insert(int index, Object obj) - at SamplesArrayList.Main() - - */ +} +/* +This code produces the following output. + +myAL does not have a fixed size. +myFixedSizeAL has a fixed size. + +Initially, +Standard : The quick brown fox jumps over the lazy dog +Fixed size: The quick brown fox jumps over the lazy dog +After Sort, +Standard : brown dog fox jumps lazy over quick the The +Fixed size: brown dog fox jumps lazy over quick the The +After Reverse, +Standard : The the quick over lazy jumps fox dog brown +Fixed size: The the quick over lazy jumps fox dog brown +After adding to the standard ArrayList, +Standard : The the quick over lazy jumps fox dog brown AddMe +Fixed size: The the quick over lazy jumps fox dog brown AddMe + +Exception: System.NotSupportedException: Collection was of a fixed size. + at System.Collections.FixedSizeArrayList.Add(Object obj) + at SamplesArrayList.Main() +Exception: System.NotSupportedException: Collection was of a fixed size. + at System.Collections.FixedSizeArrayList.Insert(int index, Object obj) + at SamplesArrayList.Main() + +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Program.cs b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Program.cs new file mode 100644 index 00000000000..cba7218c693 --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Program.cs @@ -0,0 +1,2 @@ +SamplesArrayList.Run(); +SamplesArrayList2.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Project.csproj index be85cf5b17f..45767948950 100644 --- a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesArrayList diff --git a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source.cs b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source.cs index 96256b926a4..aaa4decf157 100644 --- a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source.cs @@ -1,29 +1,27 @@ // - using System; - using System.Collections; - public class SamplesArrayList { +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Run() + { - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); + // Creates and initializes a new ArrayList. + ArrayList myAL = ["The", "quick", "brown", "fox"]; - // Creates a synchronized wrapper around the ArrayList. - ArrayList mySyncdAL = ArrayList.Synchronized( myAL ); + // Creates a synchronized wrapper around the ArrayList. + ArrayList mySyncdAL = ArrayList.Synchronized(myAL); - // Displays the sychronization status of both ArrayLists. - Console.WriteLine( "myAL is {0}.", myAL.IsSynchronized ? "synchronized" : "not synchronized" ); - Console.WriteLine( "mySyncdAL is {0}.", mySyncdAL.IsSynchronized ? "synchronized" : "not synchronized" ); + // Displays the synchronization status of both ArrayLists. + Console.WriteLine($"myAL is {(myAL.IsSynchronized ? "synchronized" : "not synchronized")}."); + Console.WriteLine($"mySyncdAL is {(mySyncdAL.IsSynchronized ? "synchronized" : "not synchronized")}."); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - myAL is not synchronized. - mySyncdAL is synchronized. - */ +myAL is not synchronized. +mySyncdAL is synchronized. +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source2.cs b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source2.cs index 35f7c6d4b59..7f8b2c665fe 100644 --- a/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source2.cs +++ b/snippets/csharp/System.Collections/ArrayList/IsSynchronized/source2.cs @@ -3,12 +3,12 @@ public class SamplesArrayList2 { - public static void Main() + public static void Run() { // - ArrayList myCollection = new ArrayList(); + ArrayList myCollection = []; - lock(myCollection.SyncRoot) + lock (myCollection.SyncRoot) { foreach (object item in myCollection) { diff --git a/snippets/csharp/System.Collections/ArrayList/Item/Program.cs b/snippets/csharp/System.Collections/ArrayList/Item/Program.cs new file mode 100644 index 00000000000..b6089c2f415 --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/Item/Program.cs @@ -0,0 +1,2 @@ +Example.Run(); +ScrambleList.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/Item/Project.csproj b/snippets/csharp/System.Collections/ArrayList/Item/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/ArrayList/Item/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/Item/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/ArrayList/Item/source.cs b/snippets/csharp/System.Collections/ArrayList/Item/source.cs index 1f7dc90176a..3af45815ba0 100644 --- a/snippets/csharp/System.Collections/ArrayList/Item/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Item/source.cs @@ -4,38 +4,30 @@ public class Example { - public static void Main() + public static void Run() { // Create an empty ArrayList, and add some elements. - ArrayList stringList = new ArrayList(); - - stringList.Add("a"); - stringList.Add("abc"); - stringList.Add("abcdef"); - stringList.Add("abcdefg"); + ArrayList stringList = ["a", "abc", "abcdef", "abcdefg"]; // The Item property is an indexer, so the property name is // not required. - Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]); + Console.WriteLine($"Element {2} is \"{stringList[2]}\""); // Assigning a value to the property changes the value of // the indexed element. stringList[2] = "abcd"; - Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]); + Console.WriteLine($"Element {2} is \"{stringList[2]}\""); // Accessing an element outside the current element count // causes an exception. - Console.WriteLine("Number of elements in the list: {0}", - stringList.Count); + Console.WriteLine($"Number of elements in the list: {stringList.Count}"); try { - Console.WriteLine("Element {0} is \"{1}\"", - stringList.Count, stringList[stringList.Count]); + Console.WriteLine($"Element {stringList.Count} is \"{stringList[stringList.Count]}\""); } - catch(ArgumentOutOfRangeException aoore) + catch (ArgumentOutOfRangeException) { - Console.WriteLine("stringList({0}) is out of range.", - stringList.Count); + Console.WriteLine($"stringList({stringList.Count}) is out of range."); } // You cannot use the Item property to add new elements. @@ -43,17 +35,15 @@ public static void Main() { stringList[stringList.Count] = "42"; } - catch(ArgumentOutOfRangeException aoore) + catch (ArgumentOutOfRangeException) { - Console.WriteLine("stringList({0}) is out of range.", - stringList.Count); + Console.WriteLine($"stringList({stringList.Count}) is out of range."); } Console.WriteLine(); for (int i = 0; i < stringList.Count; i++) { - Console.WriteLine("Element {0} is \"{1}\"", i, - stringList[i]); + Console.WriteLine($"Element {i} is \"{stringList[i]}\""); } Console.WriteLine(); diff --git a/snippets/csharp/System.Collections/ArrayList/Item/source2.cs b/snippets/csharp/System.Collections/ArrayList/Item/source2.cs index 5a84ec2421d..ae55a0a159c 100644 --- a/snippets/csharp/System.Collections/ArrayList/Item/source2.cs +++ b/snippets/csharp/System.Collections/ArrayList/Item/source2.cs @@ -4,10 +4,10 @@ public class ScrambleList : ArrayList { - public static void Main() + public static void Run() { // Create an empty ArrayList, and add some elements. - ScrambleList integerList = new ScrambleList(); + ScrambleList integerList = []; for (int i = 0; i < 10; i++) { @@ -17,7 +17,7 @@ public static void Main() Console.WriteLine("Ordered:\n"); foreach (int value in integerList) { - Console.Write("{0}, ", value); + Console.Write($"{value}, "); } Console.WriteLine("\n\nScrambled:\n"); @@ -26,7 +26,7 @@ public static void Main() foreach (int value in integerList) { - Console.Write("{0}, ", value); + Console.Write($"{value}, "); } Console.WriteLine("\n"); } @@ -36,7 +36,7 @@ public void Scramble() int limit = this.Count; int temp; int swapindex; - Random rnd = new Random(); + Random rnd = new(); for (int i = 0; i < limit; i++) { // The Item property of ArrayList is the default indexer. Thus, diff --git a/snippets/csharp/System.Collections/ArrayList/LastIndexOf/source.cs b/snippets/csharp/System.Collections/ArrayList/LastIndexOf/source.cs index c29fcce953c..cc5456d2204 100644 --- a/snippets/csharp/System.Collections/ArrayList/LastIndexOf/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/LastIndexOf/source.cs @@ -1,71 +1,79 @@ -// - using System; - using System.Collections; - public class SamplesArrayList { +// +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new ArrayList with three elements of the same value. - ArrayList myAL = new ArrayList(); - myAL.Add( "the" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); - myAL.Add( "in" ); - myAL.Add( "the" ); - myAL.Add( "barn" ); + // Creates and initializes a new ArrayList with three elements of the same value. + ArrayList myAL = + [ + "the", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + "in", + "the", + "barn", + ]; - // Displays the values of the ArrayList. - Console.WriteLine( "The ArrayList contains the following values:" ); - PrintIndexAndValues( myAL ); + // Displays the values of the ArrayList. + Console.WriteLine("The ArrayList contains the following values:"); + PrintIndexAndValues(myAL); - // Searches for the last occurrence of the duplicated value. - string myString = "the"; - int myIndex = myAL.LastIndexOf( myString ); - Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex ); + // Searches for the last occurrence of the duplicated value. + string myString = "the"; + int myIndex = myAL.LastIndexOf(myString); + Console.WriteLine($"The last occurrence of \"{myString}\" is at index {myIndex}."); - // Searches for the last occurrence of the duplicated value in the first section of the ArrayList. - myIndex = myAL.LastIndexOf( myString, 8 ); - Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex ); + // Searches for the last occurrence of the duplicated value in the first section of the ArrayList. + myIndex = myAL.LastIndexOf(myString, 8); + Console.WriteLine($"The last occurrence of \"{myString}\" between the start and index 8 is at index {myIndex}."); - // Searches for the last occurrence of the duplicated value in a section of the ArrayList. Note that the start index is greater than the end index because the search is done backward. - myIndex = myAL.LastIndexOf( myString, 10, 6 ); - Console.WriteLine( "The last occurrence of \"{0}\" between index 10 and index 5 is at index {1}.", myString, myIndex ); + // Searches for the last occurrence of the duplicated value in a section of the ArrayList. Note that the start index is greater than the end index because the search is done backward. + myIndex = myAL.LastIndexOf(myString, 10, 6); + Console.WriteLine($"The last occurrence of \"{myString}\" between index 10 and index 5 is at index {myIndex}."); } - public static void PrintIndexAndValues( IEnumerable myList ) { - int i = 0; - foreach ( Object obj in myList ) - Console.WriteLine( " [{0}]: {1}", i++, obj ); - Console.WriteLine(); + public static void PrintIndexAndValues(IEnumerable myList) + { + int i = 0; + foreach (object obj in myList) + { + Console.WriteLine($" [{i++}]: {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The ArrayList contains the following values: - [0]: the - [1]: quick - [2]: brown - [3]: fox - [4]: jumps - [5]: over - [6]: the - [7]: lazy - [8]: dog - [9]: in - [10]: the - [11]: barn +The ArrayList contains the following values: + [0]: the + [1]: quick + [2]: brown + [3]: fox + [4]: jumps + [5]: over + [6]: the + [7]: lazy + [8]: dog + [9]: in + [10]: the + [11]: barn - The last occurrence of "the" is at index 10. - The last occurrence of "the" between the start and index 8 is at index 6. - The last occurrence of "the" between index 10 and index 5 is at index 10. - */ +The last occurrence of "the" is at index 10. +The last occurrence of "the" between the start and index 8 is at index 6. +The last occurrence of "the" between index 10 and index 5 is at index 10. +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/Overview/source.cs b/snippets/csharp/System.Collections/ArrayList/Overview/source.cs index 7d267abb813..7b76c6e33e9 100644 --- a/snippets/csharp/System.Collections/ArrayList/Overview/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Overview/source.cs @@ -1,39 +1,42 @@ // - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("Hello"); - myAL.Add("World"); - myAL.Add("!"); - - // Displays the properties and values of the ArrayList. - Console.WriteLine( "myAL" ); - Console.WriteLine( " Count: {0}", myAL.Count ); - Console.WriteLine( " Capacity: {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = ["Hello", "World", "!"]; + + // Displays the properties and values of the ArrayList. + Console.WriteLine("myAL"); + Console.WriteLine($" Count: {myAL.Count}"); + Console.WriteLine($" Capacity: {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces output similar to the following: +/* +This code produces output similar to the following: - myAL - Count: 3 - Capacity: 4 - Values: Hello World ! +myAL + Count: 3 + Capacity: 4 + Values: Hello World ! - */ +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/ReadOnly/source.cs b/snippets/csharp/System.Collections/ArrayList/ReadOnly/source.cs index 9b8f066c15c..685275b5381 100644 --- a/snippets/csharp/System.Collections/ArrayList/ReadOnly/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/ReadOnly/source.cs @@ -1,53 +1,65 @@ -// - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "red" ); - myAL.Add( "orange" ); - myAL.Add( "yellow" ); - - // Creates a read-only copy of the ArrayList. - ArrayList myReadOnlyAL = ArrayList.ReadOnly( myAL ); - - // Displays whether the ArrayList is read-only or writable. - Console.WriteLine( "myAL is {0}.", myAL.IsReadOnly ? "read-only" : "writable" ); - Console.WriteLine( "myReadOnlyAL is {0}.", myReadOnlyAL.IsReadOnly ? "read-only" : "writable" ); - - // Displays the contents of both collections. - Console.WriteLine( "\nInitially," ); - Console.WriteLine( "The original ArrayList myAL contains:" ); - foreach ( string myStr in myAL ) - Console.WriteLine( " {0}", myStr ); - Console.WriteLine( "The read-only ArrayList myReadOnlyAL contains:" ); - foreach ( string myStr in myReadOnlyAL ) - Console.WriteLine( " {0}", myStr ); - - // Adding an element to a read-only ArrayList throws an exception. - Console.WriteLine( "\nTrying to add a new element to the read-only ArrayList:" ); - try { - myReadOnlyAL.Add("green"); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } - - // Adding an element to the original ArrayList affects the read-only ArrayList. - myAL.Add( "blue" ); - - // Displays the contents of both collections again. - Console.WriteLine( "\nAfter adding a new element to the original ArrayList," ); - Console.WriteLine( "The original ArrayList myAL contains:" ); - foreach ( string myStr in myAL ) - Console.WriteLine( " {0}", myStr ); - Console.WriteLine( "The read-only ArrayList myReadOnlyAL contains:" ); - foreach ( string myStr in myReadOnlyAL ) - Console.WriteLine( " {0}", myStr ); +// +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = ["red", "orange", "yellow"]; + + // Creates a read-only copy of the ArrayList. + ArrayList myReadOnlyAL = ArrayList.ReadOnly(myAL); + + // Displays whether the ArrayList is read-only or writable. + Console.WriteLine($"myAL is {(myAL.IsReadOnly ? "read-only" : "writable")}."); + Console.WriteLine($"myReadOnlyAL is {(myReadOnlyAL.IsReadOnly ? "read-only" : "writable")}."); + + // Displays the contents of both collections. + Console.WriteLine("\nInitially,"); + Console.WriteLine("The original ArrayList myAL contains:"); + foreach (string myStr in myAL) + { + Console.WriteLine($" {myStr}"); + } + + Console.WriteLine("The read-only ArrayList myReadOnlyAL contains:"); + foreach (string myStr in myReadOnlyAL) + { + Console.WriteLine($" {myStr}"); + } + + // Adding an element to a read-only ArrayList throws an exception. + Console.WriteLine("\nTrying to add a new element to the read-only ArrayList:"); + try + { + myReadOnlyAL.Add("green"); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } + + // Adding an element to the original ArrayList affects the read-only ArrayList. + myAL.Add("blue"); + + // Displays the contents of both collections again. + Console.WriteLine("\nAfter adding a new element to the original ArrayList,"); + Console.WriteLine("The original ArrayList myAL contains:"); + foreach (string myStr in myAL) + { + Console.WriteLine($" {myStr}"); + } + + Console.WriteLine("The read-only ArrayList myReadOnlyAL contains:"); + foreach (string myStr in myReadOnlyAL) + { + Console.WriteLine($" {myStr}"); + } } - } +} /* diff --git a/snippets/csharp/System.Collections/ArrayList/Remove/source.cs b/snippets/csharp/System.Collections/ArrayList/Remove/source.cs index a6b3935c277..ccb13d3a557 100644 --- a/snippets/csharp/System.Collections/ArrayList/Remove/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Remove/source.cs @@ -1,64 +1,72 @@ // - using System; - using System.Collections; - public class SamplesArrayList { +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; - // Displays the ArrayList. - Console.WriteLine( "The ArrayList initially contains the following:" ); - PrintValues( myAL ); + // Displays the ArrayList. + Console.WriteLine("The ArrayList initially contains the following:"); + PrintValues(myAL); - // Removes the element containing "lazy". - myAL.Remove( "lazy" ); + // Removes the element containing "lazy". + myAL.Remove("lazy"); - // Displays the current state of the ArrayList. - Console.WriteLine( "After removing \"lazy\":" ); - PrintValues( myAL ); + // Displays the current state of the ArrayList. + Console.WriteLine("After removing \"lazy\":"); + PrintValues(myAL); - // Removes the element at index 5. - myAL.RemoveAt( 5 ); + // Removes the element at index 5. + myAL.RemoveAt(5); - // Displays the current state of the ArrayList. - Console.WriteLine( "After removing the element at index 5:" ); - PrintValues( myAL ); + // Displays the current state of the ArrayList. + Console.WriteLine("After removing the element at index 5:"); + PrintValues(myAL); - // Removes three elements starting at index 4. - myAL.RemoveRange( 4, 3 ); + // Removes three elements starting at index 4. + myAL.RemoveRange(4, 3); - // Displays the current state of the ArrayList. - Console.WriteLine( "After removing three elements starting at index 4:" ); - PrintValues( myAL ); + // Displays the current state of the ArrayList. + Console.WriteLine("After removing three elements starting at index 4:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The ArrayList initially contains the following: - The quick brown fox jumps over the lazy dog - After removing "lazy": - The quick brown fox jumps over the dog - After removing the element at index 5: - The quick brown fox jumps the dog - After removing three elements starting at index 4: - The quick brown fox - */ +The ArrayList initially contains the following: + The quick brown fox jumps over the lazy dog +After removing "lazy": + The quick brown fox jumps over the dog +After removing the element at index 5: + The quick brown fox jumps the dog +After removing three elements starting at index 4: + The quick brown fox +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/Repeat/source.cs b/snippets/csharp/System.Collections/ArrayList/Repeat/source.cs index 6259e9af625..5837863414c 100644 --- a/snippets/csharp/System.Collections/ArrayList/Repeat/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Repeat/source.cs @@ -1,48 +1,54 @@ // - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates a new ArrayList with five elements and initialize each element with a null value. - ArrayList myAL = ArrayList.Repeat( null, 5 ); - - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "ArrayList with five elements with a null value" ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); - - // Creates a new ArrayList with seven elements and initialize each element with the string "abc". - myAL = ArrayList.Repeat( "abc", 7 ); - - // Displays the count, capacity and values of the ArrayList. - Console.WriteLine( "ArrayList with seven elements with a string value" ); - Console.WriteLine( " Count : {0}", myAL.Count ); - Console.WriteLine( " Capacity : {0}", myAL.Capacity ); - Console.Write( " Values:" ); - PrintValues( myAL ); +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates a new ArrayList with five elements and initializes each element with a null value. + ArrayList myAL = ArrayList.Repeat(null, 5); + + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("ArrayList with five elements with a null value"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); + + // Creates a new ArrayList with seven elements and initializes each element with the string "abc". + myAL = ArrayList.Repeat("abc", 7); + + // Displays the count, capacity and values of the ArrayList. + Console.WriteLine("ArrayList with seven elements with a string value"); + Console.WriteLine($" Count : {myAL.Count}"); + Console.WriteLine($" Capacity : {myAL.Capacity}"); + Console.Write(" Values:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. - - ArrayList with five elements with a null value - Count : 5 - Capacity : 16 - Values: - ArrayList with seven elements with a string value - Count : 7 - Capacity : 16 - Values: abc abc abc abc abc abc abc - - */ +} +/* +This code produces the following output. + +ArrayList with five elements with a null value + Count : 5 + Capacity : 16 + Values: +ArrayList with seven elements with a string value + Count : 7 + Capacity : 16 + Values: abc abc abc abc abc abc abc + +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/Reverse/Program.cs b/snippets/csharp/System.Collections/ArrayList/Reverse/Program.cs new file mode 100644 index 00000000000..7640237e558 --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/Reverse/Program.cs @@ -0,0 +1,2 @@ +SamplesArrayList.Run(); +SamplesArrayList1.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/Reverse/Project.csproj b/snippets/csharp/System.Collections/ArrayList/Reverse/Project.csproj index be85cf5b17f..45767948950 100644 --- a/snippets/csharp/System.Collections/ArrayList/Reverse/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/Reverse/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesArrayList diff --git a/snippets/csharp/System.Collections/ArrayList/Reverse/source.cs b/snippets/csharp/System.Collections/ArrayList/Reverse/source.cs index 49fa5016c81..7fd99cc2ca1 100644 --- a/snippets/csharp/System.Collections/ArrayList/Reverse/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Reverse/source.cs @@ -1,65 +1,73 @@ // - using System; - using System.Collections; - public class SamplesArrayList { +using System; +using System.Collections; +public class SamplesArrayList +{ - public static void Main() { + public static void Run() + { - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; - // Displays the values of the ArrayList. - Console.WriteLine( "The ArrayList initially contains the following values:" ); - PrintValues( myAL ); + // Displays the values of the ArrayList. + Console.WriteLine("The ArrayList initially contains the following values:"); + PrintValues(myAL); - // Reverses the sort order of the values of the ArrayList. - myAL.Reverse(); + // Reverses the sort order of the values of the ArrayList. + myAL.Reverse(); - // Displays the values of the ArrayList. - Console.WriteLine( "After reversing:" ); - PrintValues( myAL ); + // Displays the values of the ArrayList. + Console.WriteLine("After reversing:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.WriteLine( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.WriteLine($" {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The ArrayList initially contains the following values: - The - quick - brown - fox - jumps - over - the - lazy - dog +The ArrayList initially contains the following values: + The + quick + brown + fox + jumps + over + the + lazy + dog - After reversing: - dog - lazy - the - over - jumps - fox - brown - quick - The - */ +After reversing: + dog + lazy + the + over + jumps + fox + brown + quick + The +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/Reverse/source1.cs b/snippets/csharp/System.Collections/ArrayList/Reverse/source1.cs index 7ca8110b381..b6e4c19c3db 100644 --- a/snippets/csharp/System.Collections/ArrayList/Reverse/source1.cs +++ b/snippets/csharp/System.Collections/ArrayList/Reverse/source1.cs @@ -1,66 +1,74 @@ // - using System; - using System.Collections; - public class SamplesArrayList1 { +using System; +using System.Collections; +public class SamplesArrayList1 +{ - public static void Main() { + public static void Run() + { - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "QUICK" ); - myAL.Add( "BROWN" ); - myAL.Add( "FOX" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "QUICK", + "BROWN", + "FOX", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; - // Displays the values of the ArrayList. - Console.WriteLine( "The ArrayList initially contains the following values:" ); - PrintValues( myAL ); + // Displays the values of the ArrayList. + Console.WriteLine("The ArrayList initially contains the following values:"); + PrintValues(myAL); - // Reverses the sort order of the values of the ArrayList. - myAL.Reverse( 1, 3 ); + // Reverses the sort order of the values of the ArrayList. + myAL.Reverse(1, 3); - // Displays the values of the ArrayList. - Console.WriteLine( "After reversing:" ); - PrintValues( myAL ); + // Displays the values of the ArrayList. + Console.WriteLine("After reversing:"); + PrintValues(myAL); } - public static void PrintValues( IEnumerable myList ) { - foreach ( Object obj in myList ) - Console.WriteLine( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList) + { + foreach (object obj in myList) + { + Console.WriteLine($" {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The ArrayList initially contains the following values: - The - QUICK - BROWN - FOX - jumps - over - the - lazy - dog +The ArrayList initially contains the following values: + The + QUICK + BROWN + FOX + jumps + over + the + lazy + dog - After reversing: - The - FOX - BROWN - QUICK - jumps - over - the - lazy - dog +After reversing: + The + FOX + BROWN + QUICK + jumps + over + the + lazy + dog - */ +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/SetRange/source.cs b/snippets/csharp/System.Collections/ArrayList/SetRange/source.cs index 6f001611e4f..886b05fa6b8 100644 --- a/snippets/csharp/System.Collections/ArrayList/SetRange/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/SetRange/source.cs @@ -1,56 +1,64 @@ // - using System; - using System.Collections; - public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); - - // Creates and initializes the source ICollection. - Queue mySourceList = new Queue(); - mySourceList.Enqueue( "big" ); - mySourceList.Enqueue( "gray" ); - mySourceList.Enqueue( "wolf" ); - - // Displays the values of five elements starting at index 0. - ArrayList mySubAL = myAL.GetRange( 0, 5 ); - Console.WriteLine( "Index 0 through 4 contains:" ); - PrintValues( mySubAL, '\t' ); - - // Replaces the values of five elements starting at index 1 with the values in the ICollection. - myAL.SetRange( 1, mySourceList ); - - // Displays the values of five elements starting at index 0. - mySubAL = myAL.GetRange( 0, 5 ); - Console.WriteLine( "Index 0 through 4 now contains:" ); - PrintValues( mySubAL, '\t' ); +using System; +using System.Collections; +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; + + // Creates and initializes the source ICollection. + Queue mySourceList = new(); + mySourceList.Enqueue("big"); + mySourceList.Enqueue("gray"); + mySourceList.Enqueue("wolf"); + + // Displays the values of five elements starting at index 0. + ArrayList mySubAL = myAL.GetRange(0, 5); + Console.WriteLine("Index 0 through 4 contains:"); + PrintValues(mySubAL, '\t'); + + // Replaces the values of five elements starting at index 1 with the values in the ICollection. + myAL.SetRange(1, mySourceList); + + // Displays the values of five elements starting at index 0. + mySubAL = myAL.GetRange(0, 5); + Console.WriteLine("Index 0 through 4 now contains:"); + PrintValues(mySubAL, '\t'); } - public static void PrintValues( IEnumerable myList, char mySeparator ) { - foreach ( Object obj in myList ) - Console.Write( "{0}{1}", mySeparator, obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, char mySeparator) + { + foreach (object obj in myList) + { + Console.Write($"{mySeparator}{obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Index 0 through 4 contains: - The quick brown fox jumps - Index 0 through 4 now contains: - The big gray wolf jumps - */ +Index 0 through 4 contains: + The quick brown fox jumps +Index 0 through 4 now contains: + The big gray wolf jumps +*/ // diff --git a/snippets/csharp/System.Collections/ArrayList/Sort/Program.cs b/snippets/csharp/System.Collections/ArrayList/Sort/Program.cs new file mode 100644 index 00000000000..6a4c92f5639 --- /dev/null +++ b/snippets/csharp/System.Collections/ArrayList/Sort/Program.cs @@ -0,0 +1,3 @@ +SamplesArrayList1.Run(); +SamplesArrayList2.Run(); +SamplesArrayList3.Run(); diff --git a/snippets/csharp/System.Collections/ArrayList/Sort/Project.csproj b/snippets/csharp/System.Collections/ArrayList/Sort/Project.csproj index 4910651c76a..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/ArrayList/Sort/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/Sort/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesArrayList1 \ No newline at end of file diff --git a/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort2.cs b/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort2.cs index 08e66dd27d7..c2406980ba5 100644 --- a/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort2.cs +++ b/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort2.cs @@ -6,28 +6,27 @@ public class SamplesArrayList2 { - public class myReverserClass : IComparer + public class ReverseComparer : IComparer { // Calls CaseInsensitiveComparer.Compare with the parameters reversed. - int IComparer.Compare(Object x, Object y) - { - return ((new CaseInsensitiveComparer()).Compare(y, x)); - } + int IComparer.Compare(object x, object y) => ((new CaseInsensitiveComparer()).Compare(y, x)); } - public static void Main() + public static void Run() { // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("The"); - myAL.Add("quick"); - myAL.Add("brown"); - myAL.Add("fox"); - myAL.Add("jumps"); - myAL.Add("over"); - myAL.Add("the"); - myAL.Add("lazy"); - myAL.Add("dog"); + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; // Displays the values of the ArrayList. Console.WriteLine("The ArrayList initially contains the following values:"); @@ -39,7 +38,7 @@ public static void Main() PrintIndexAndValues(myAL); // Sorts the values of the ArrayList using the reverse case-insensitive comparer. - IComparer myComparer = new myReverserClass(); + IComparer myComparer = new ReverseComparer(); myAL.Sort(myComparer); Console.WriteLine("After sorting with the reverse case-insensitive comparer:"); PrintIndexAndValues(myAL); @@ -48,8 +47,11 @@ public static void Main() public static void PrintIndexAndValues(IEnumerable myList) { int i = 0; - foreach (Object obj in myList) - Console.WriteLine("\t[{0}]:\t{1}", i++, obj); + foreach (object obj in myList) + { + Console.WriteLine($"\t[{i++}]:\t{obj}"); + } + Console.WriteLine(); } } diff --git a/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort3.cs b/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort3.cs index e28b9b85651..bab3cafc60b 100644 --- a/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort3.cs +++ b/snippets/csharp/System.Collections/ArrayList/Sort/arraylist_sort3.cs @@ -6,28 +6,27 @@ public class SamplesArrayList3 { - public class myReverserClass : IComparer + public class ReverseCaseInsensitiveComparer : IComparer { // Calls CaseInsensitiveComparer.Compare with the parameters reversed. - int IComparer.Compare(Object x, Object y) - { - return ((new CaseInsensitiveComparer()).Compare(y, x)); - } + int IComparer.Compare(object x, object y) => ((new CaseInsensitiveComparer()).Compare(y, x)); } - public static void Main() + public static void Run() { // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("The"); - myAL.Add("QUICK"); - myAL.Add("BROWN"); - myAL.Add("FOX"); - myAL.Add("jumps"); - myAL.Add("over"); - myAL.Add("the"); - myAL.Add("lazy"); - myAL.Add("dog"); + ArrayList myAL = + [ + "The", + "QUICK", + "BROWN", + "FOX", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; // Displays the values of the ArrayList. Console.WriteLine("The ArrayList initially contains the following values:"); @@ -39,7 +38,7 @@ public static void Main() PrintIndexAndValues(myAL); // Sorts the values of the ArrayList using the reverse case-insensitive comparer. - IComparer myComparer = new myReverserClass(); + IComparer myComparer = new ReverseCaseInsensitiveComparer(); myAL.Sort(1, 3, myComparer); Console.WriteLine("After sorting from index 1 to index 3 with the reverse case-insensitive comparer:"); PrintIndexAndValues(myAL); @@ -48,8 +47,11 @@ public static void Main() public static void PrintIndexAndValues(IEnumerable myList) { int i = 0; - foreach (Object obj in myList) - Console.WriteLine("\t[{0}]:\t{1}", i++, obj); + foreach (object obj in myList) + { + Console.WriteLine($"\t[{i++}]:\t{obj}"); + } + Console.WriteLine(); } } diff --git a/snippets/csharp/System.Collections/ArrayList/Sort/source.cs b/snippets/csharp/System.Collections/ArrayList/Sort/source.cs index 035eef18fb6..fb3b7b21570 100644 --- a/snippets/csharp/System.Collections/ArrayList/Sort/source.cs +++ b/snippets/csharp/System.Collections/ArrayList/Sort/source.cs @@ -4,19 +4,21 @@ public class SamplesArrayList1 { - public static void Main() + public static void Run() { // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("The"); - myAL.Add("quick"); - myAL.Add("brown"); - myAL.Add("fox"); - myAL.Add("jumps"); - myAL.Add("over"); - myAL.Add("the"); - myAL.Add("lazy"); - myAL.Add("dog"); + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; // Displays the values of the ArrayList. Console.WriteLine("The ArrayList initially contains the following values:"); @@ -32,8 +34,11 @@ public static void Main() public static void PrintValues(IEnumerable myList) { - foreach (Object obj in myList) - Console.WriteLine(" {0}", obj); + foreach (object obj in myList) + { + Console.WriteLine($" {obj}"); + } + Console.WriteLine(); } } diff --git a/snippets/csharp/System.Collections/ArrayList/ToArray/Project.csproj b/snippets/csharp/System.Collections/ArrayList/ToArray/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/ArrayList/ToArray/Project.csproj +++ b/snippets/csharp/System.Collections/ArrayList/ToArray/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/ArrayList/ToArray/arraylist_toarray.cs b/snippets/csharp/System.Collections/ArrayList/ToArray/arraylist_toarray.cs index 1ab086b510c..502d4992759 100644 --- a/snippets/csharp/System.Collections/ArrayList/ToArray/arraylist_toarray.cs +++ b/snippets/csharp/System.Collections/ArrayList/ToArray/arraylist_toarray.cs @@ -4,46 +4,58 @@ using System; using System.Collections; -public class SamplesArrayList { - - public static void Main() { - - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "The" ); - myAL.Add( "quick" ); - myAL.Add( "brown" ); - myAL.Add( "fox" ); - myAL.Add( "jumps" ); - myAL.Add( "over" ); - myAL.Add( "the" ); - myAL.Add( "lazy" ); - myAL.Add( "dog" ); - - // Displays the values of the ArrayList. - Console.WriteLine( "The ArrayList contains the following values:" ); - PrintIndexAndValues( myAL ); - - // Copies the elements of the ArrayList to a string array. - String[] myArr = (String[]) myAL.ToArray( typeof( string ) ); - - // Displays the contents of the string array. - Console.WriteLine( "The string array contains the following values:" ); - PrintIndexAndValues( myArr ); - } - - public static void PrintIndexAndValues( ArrayList myList ) { - int i = 0; - foreach ( Object o in myList ) - Console.WriteLine( "\t[{0}]:\t{1}", i++, o ); - Console.WriteLine(); - } - - public static void PrintIndexAndValues( String[] myArr ) { - for ( int i = 0; i < myArr.Length; i++ ) - Console.WriteLine( "\t[{0}]:\t{1}", i, myArr[i] ); - Console.WriteLine(); - } +public class SamplesArrayList +{ + + public static void Main() + { + + // Creates and initializes a new ArrayList. + ArrayList myAL = + [ + "The", + "quick", + "brown", + "fox", + "jumps", + "over", + "the", + "lazy", + "dog", + ]; + + // Displays the values of the ArrayList. + Console.WriteLine("The ArrayList contains the following values:"); + PrintIndexAndValues(myAL); + + // Copies the elements of the ArrayList to a string array. + string[] myArr = (string[])myAL.ToArray(typeof(string)); + + // Displays the contents of the string array. + Console.WriteLine("The string array contains the following values:"); + PrintIndexAndValues(myArr); + } + + public static void PrintIndexAndValues(ArrayList myList) + { + int i = 0; + foreach (object o in myList) + { + Console.WriteLine($"\t[{i++}]:\t{o}"); + } + + Console.WriteLine(); + } + + public static void PrintIndexAndValues(string[] myArr) + { + for (int i = 0; i < myArr.Length; i++) + { + Console.WriteLine($"\t[{i}]:\t{myArr[i]}"); + } + + Console.WriteLine(); + } } diff --git a/snippets/csharp/System.Collections/BitArray/And/source.cs b/snippets/csharp/System.Collections/BitArray/And/source.cs index eafe7fbadc8..8718acd9cd9 100644 --- a/snippets/csharp/System.Collections/BitArray/And/source.cs +++ b/snippets/csharp/System.Collections/BitArray/And/source.cs @@ -1,80 +1,88 @@ // - using System; - using System.Collections; - public class SamplesBitArray { +using System; +using System.Collections; +public class SamplesBitArray +{ - public static void Main() { + public static void Main() + { - // Creates and initializes two BitArrays of the same size. - BitArray myBA1 = new BitArray( 4 ); - BitArray myBA2 = new BitArray( 4 ); - myBA1[0] = myBA1[1] = false; - myBA1[2] = myBA1[3] = true; - myBA2[0] = myBA2[2] = false; - myBA2[1] = myBA2[3] = true; + // Creates and initializes two BitArrays of the same size. + BitArray myBA1 = new(4); + BitArray myBA2 = new(4); + myBA1[0] = myBA1[1] = false; + myBA1[2] = myBA1[3] = true; + myBA2[0] = myBA2[2] = false; + myBA2[1] = myBA2[3] = true; - // Performs a bitwise AND operation between BitArray instances of the same size. - Console.WriteLine( "Initial values" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + // Performs a bitwise AND operation between BitArray instances of the same size. + Console.WriteLine("Initial values"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - Console.WriteLine( "Result" ); - Console.Write( "AND:" ); - PrintValues( myBA1.And( myBA2 ), 8 ); - Console.WriteLine(); + Console.WriteLine("Result"); + Console.Write("AND:"); + PrintValues(myBA1.And(myBA2), 8); + Console.WriteLine(); - Console.WriteLine( "After AND" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + Console.WriteLine("After AND"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - // Performing AND between BitArray instances of different sizes returns an exception. - try { - BitArray myBA3 = new BitArray( 8 ); - myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; - myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; - myBA1.And( myBA3 ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } + // Performing AND between BitArray instances of different sizes returns an exception. + try + { + BitArray myBA3 = new(8); + myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; + myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; + myBA1.And(myBA3); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myList, int myWidth ) { - int i = myWidth; - foreach ( Object obj in myList ) { - if ( i <= 0 ) { - i = myWidth; - Console.WriteLine(); - } - i--; - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, int myWidth) + { + int i = myWidth; + foreach (object obj in myList) + { + if (i <= 0) + { + i = myWidth; + Console.WriteLine(); + } + i--; + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initial values - myBA1: False False True True - myBA2: False True False True +Initial values +myBA1: False False True True +myBA2: False True False True - Result - AND: False False False True +Result +AND: False False False True - After AND - myBA1: False False False True - myBA2: False True False True +After AND +myBA1: False False False True +myBA2: False True False True - Exception: System.ArgumentException: Array lengths must be the same. - at System.Collections.BitArray.And(BitArray value) - at SamplesBitArray.Main() - */ +Exception: System.ArgumentException: Array lengths must be the same. + at System.Collections.BitArray.And(BitArray value) + at SamplesBitArray.Main() +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/CopyTo/source.cs b/snippets/csharp/System.Collections/BitArray/CopyTo/source.cs index a007780a446..c574a9c98f3 100644 --- a/snippets/csharp/System.Collections/BitArray/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/BitArray/CopyTo/source.cs @@ -1,94 +1,101 @@ -// - using System; - using System.Collections; - public class SamplesBitArray { - - public static void Main() { - - // Creates and initializes the source BitArray. - BitArray myBA = new BitArray( 4 ); - myBA[0] = myBA[1] = myBA[2] = myBA[3] = true; - - // Creates and initializes the one-dimensional target Array of type Boolean. - bool[] myBoolArray = new bool[8]; - myBoolArray[0] = false; - myBoolArray[1] = false; - - // Displays the values of the target Array. - Console.WriteLine( "The target Boolean Array contains the following (before and after copying):" ); - PrintValues( myBoolArray ); - - // Copies the entire source BitArray to the target BitArray, starting at index 3. - myBA.CopyTo( myBoolArray, 3 ); - - // Displays the values of the target Array. - PrintValues( myBoolArray ); - - // Creates and initializes the one-dimensional target Array of type integer. - int[] myIntArray = new int[8]; - myIntArray[0] = 42; - myIntArray[1] = 43; - - // Displays the values of the target Array. - Console.WriteLine( "The target integer Array contains the following (before and after copying):" ); - PrintValues( myIntArray ); - - // Copies the entire source BitArray to the target BitArray, starting at index 3. - myBA.CopyTo( myIntArray, 3 ); - - // Displays the values of the target Array. - PrintValues( myIntArray ); - - // Creates and initializes the one-dimensional target Array of type byte. - Array myByteArray = Array.CreateInstance( typeof(byte), 8 ); - myByteArray.SetValue( (byte) 10, 0 ); - myByteArray.SetValue( (byte) 11, 1 ); - - // Displays the values of the target Array. - Console.WriteLine( "The target byte Array contains the following (before and after copying):" ); - PrintValues( myByteArray ); - - // Copies the entire source BitArray to the target BitArray, starting at index 3. - myBA.CopyTo( myByteArray, 3 ); - - // Displays the values of the target Array. - PrintValues( myByteArray ); - - // Returns an exception if the array is not of type Boolean, integer or byte. - try { - Array myStringArray=Array.CreateInstance( typeof(string), 8 ); - myStringArray.SetValue( "Hello", 0 ); - myStringArray.SetValue( "World", 1 ); - myBA.CopyTo( myStringArray, 3 ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } +// +using System; +using System.Collections; +public class SamplesBitArray +{ + + public static void Main() + { + + // Creates and initializes the source BitArray. + BitArray myBA = new(4); + myBA[0] = myBA[1] = myBA[2] = myBA[3] = true; + + // Creates and initializes the one-dimensional target Array of type bool. + bool[] myBoolArray = new bool[8]; + myBoolArray[0] = false; + myBoolArray[1] = false; + + // Displays the values of the target Array. + Console.WriteLine("The target bool Array contains the following (before and after copying):"); + PrintValues(myBoolArray); + + // Copies the entire source BitArray to the target BitArray, starting at index 3. + myBA.CopyTo(myBoolArray, 3); + + // Displays the values of the target Array. + PrintValues(myBoolArray); + + // Creates and initializes the one-dimensional target Array of type integer. + int[] myIntArray = new int[8]; + myIntArray[0] = 42; + myIntArray[1] = 43; + + // Displays the values of the target Array. + Console.WriteLine("The target integer Array contains the following (before and after copying):"); + PrintValues(myIntArray); + + // Copies the entire source BitArray to the target BitArray, starting at index 3. + myBA.CopyTo(myIntArray, 3); + + // Displays the values of the target Array. + PrintValues(myIntArray); + + // Creates and initializes the one-dimensional target Array of type byte. + Array myByteArray = Array.CreateInstance(typeof(byte), 8); + myByteArray.SetValue((byte)10, 0); + myByteArray.SetValue((byte)11, 1); + + // Displays the values of the target Array. + Console.WriteLine("The target byte Array contains the following (before and after copying):"); + PrintValues(myByteArray); + + // Copies the entire source BitArray to the target BitArray, starting at index 3. + myBA.CopyTo(myByteArray, 3); + + // Displays the values of the target Array. + PrintValues(myByteArray); + + // Returns an exception if the array is not of type bool, integer or byte. + try + { + Array myStringArray = Array.CreateInstance(typeof(string), 8); + myStringArray.SetValue("Hello", 0); + myStringArray.SetValue("World", 1); + myBA.CopyTo(myStringArray, 3); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myArr ) { - foreach ( Object obj in myArr ) { - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myArr) + { + foreach (object obj in myArr) + { + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } - - - /* - This code produces the following output. - - The target Boolean Array contains the following (before and after copying): - False False False False False False False False - False False False True True True True False - The target integer Array contains the following (before and after copying): - 42 43 0 0 0 0 0 0 - 42 43 0 15 0 0 0 0 - The target byte Array contains the following (before and after copying): - 10 11 0 0 0 0 0 0 - 10 11 0 15 0 0 0 0 - Exception: System.ArgumentException: Only supported array types for CopyTo on BitArrays are Boolean[], Int32[] and Byte[]. - at System.Collections.BitArray.CopyTo(Array array, int index) - at SamplesBitArray.Main() - - */ +} + + +/* +This code produces the following output. + +The target bool Array contains the following (before and after copying): + False False False False False False False False + False False False True True True True False +The target integer Array contains the following (before and after copying): + 42 43 0 0 0 0 0 0 + 42 43 0 15 0 0 0 0 +The target byte Array contains the following (before and after copying): + 10 11 0 0 0 0 0 0 + 10 11 0 15 0 0 0 0 +Exception: System.ArgumentException: Only supported array types for CopyTo on BitArrays are bool[], int[] and byte[]. + at System.Collections.BitArray.CopyTo(Array array, int index) + at SamplesBitArray.Main() + +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/Get/source.cs b/snippets/csharp/System.Collections/BitArray/Get/source.cs index e84d0ab356d..8bf9f156ab5 100644 --- a/snippets/csharp/System.Collections/BitArray/Get/source.cs +++ b/snippets/csharp/System.Collections/BitArray/Get/source.cs @@ -1,72 +1,76 @@ // - using System; - using System.Collections; - public class SamplesBitArray { +using System; +using System.Collections; +public class SamplesBitArray +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a BitArray. - BitArray myBA = new BitArray( 5 ); + // Creates and initializes a BitArray. + BitArray myBA = new(5); - // Displays the properties and values of the BitArray. - Console.WriteLine( "myBA values:" ); - PrintIndexAndValues( myBA ); + // Displays the properties and values of the BitArray. + Console.WriteLine("myBA values:"); + PrintIndexAndValues(myBA); - // Sets all the elements to true. - myBA.SetAll( true ); + // Sets all the elements to true. + myBA.SetAll(true); - // Displays the properties and values of the BitArray. - Console.WriteLine( "After setting all elements to true," ); - PrintIndexAndValues( myBA ); + // Displays the properties and values of the BitArray. + Console.WriteLine("After setting all elements to true,"); + PrintIndexAndValues(myBA); - // Sets the last index to false. - myBA.Set( myBA.Count - 1, false ); + // Sets the last index to false. + myBA.Set(myBA.Count - 1, false); - // Displays the properties and values of the BitArray. - Console.WriteLine( "After setting the last element to false," ); - PrintIndexAndValues( myBA ); + // Displays the properties and values of the BitArray. + Console.WriteLine("After setting the last element to false,"); + PrintIndexAndValues(myBA); - // Gets the value of the last two elements. - Console.WriteLine( "The last two elements are: " ); - Console.WriteLine( " at index {0} : {1}", myBA.Count - 2, myBA.Get( myBA.Count - 2 ) ); - Console.WriteLine( " at index {0} : {1}", myBA.Count - 1, myBA.Get( myBA.Count - 1 ) ); + // Gets the value of the last two elements. + Console.WriteLine("The last two elements are: "); + Console.WriteLine($" at index {myBA.Count - 2} : {myBA.Get(myBA.Count - 2)}"); + Console.WriteLine($" at index {myBA.Count - 1} : {myBA.Get(myBA.Count - 1)}"); } - public static void PrintIndexAndValues( IEnumerable myCol ) { - int i = 0; - foreach ( Object obj in myCol ) { - Console.WriteLine( " [{0}]: {1}", i++, obj ); - } - Console.WriteLine(); + public static void PrintIndexAndValues(IEnumerable myCol) + { + int i = 0; + foreach (object obj in myCol) + { + Console.WriteLine($" [{i++}]: {obj}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - myBA values: - [0]: False - [1]: False - [2]: False - [3]: False - [4]: False +myBA values: + [0]: False + [1]: False + [2]: False + [3]: False + [4]: False - After setting all elements to true, - [0]: True - [1]: True - [2]: True - [3]: True - [4]: True +After setting all elements to true, + [0]: True + [1]: True + [2]: True + [3]: True + [4]: True - After setting the last element to false, - [0]: True - [1]: True - [2]: True - [3]: True - [4]: False +After setting the last element to false, + [0]: True + [1]: True + [2]: True + [3]: True + [4]: False - The last two elements are: - at index 3 : True - at index 4 : False +The last two elements are: + at index 3 : True + at index 4 : False - */ +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/Not/source.cs b/snippets/csharp/System.Collections/BitArray/Not/source.cs index 52ae03833fd..a34dd51265f 100644 --- a/snippets/csharp/System.Collections/BitArray/Not/source.cs +++ b/snippets/csharp/System.Collections/BitArray/Not/source.cs @@ -1,62 +1,67 @@ // - using System; - using System.Collections; - public class SamplesBitArray { - - public static void Main() { - - // Creates and initializes two BitArrays of the same size. - BitArray myBA1 = new BitArray( 4 ); - BitArray myBA2 = new BitArray( 4 ); - myBA1[0] = myBA1[1] = false; - myBA1[2] = myBA1[3] = true; - myBA2[0] = myBA2[2] = false; - myBA2[1] = myBA2[3] = true; - - // Performs a bitwise NOT operation between BitArray instances of the same size. - Console.WriteLine( "Initial values" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); - - myBA1.Not(); - myBA2.Not(); - - Console.WriteLine( "After NOT" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); +using System; +using System.Collections; +public class SamplesBitArray +{ + + public static void Main() + { + + // Creates and initializes two BitArrays of the same size. + BitArray myBA1 = new(4); + BitArray myBA2 = new(4); + myBA1[0] = myBA1[1] = false; + myBA1[2] = myBA1[3] = true; + myBA2[0] = myBA2[2] = false; + myBA2[1] = myBA2[3] = true; + + // Performs a bitwise NOT operation between BitArray instances of the same size. + Console.WriteLine("Initial values"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); + + myBA1.Not(); + myBA2.Not(); + + Console.WriteLine("After NOT"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); } - public static void PrintValues( IEnumerable myList, int myWidth ) { - int i = myWidth; - foreach ( Object obj in myList ) { - if ( i <= 0 ) { - i = myWidth; - Console.WriteLine(); - } - i--; - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, int myWidth) + { + int i = myWidth; + foreach (object obj in myList) + { + if (i <= 0) + { + i = myWidth; + Console.WriteLine(); + } + i--; + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initial values - myBA1: False False True True - myBA2: False True False True +Initial values +myBA1: False False True True +myBA2: False True False True - After NOT - myBA1: True True False False - myBA2: True False True False +After NOT +myBA1: True True False False +myBA2: True False True False - */ +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/Or/source.cs b/snippets/csharp/System.Collections/BitArray/Or/source.cs index 78227c875e5..3629c1d8075 100644 --- a/snippets/csharp/System.Collections/BitArray/Or/source.cs +++ b/snippets/csharp/System.Collections/BitArray/Or/source.cs @@ -1,81 +1,89 @@ // - using System; - using System.Collections; - public class SamplesBitArray { +using System; +using System.Collections; +public class SamplesBitArray +{ - public static void Main() { + public static void Main() + { - // Creates and initializes two BitArrays of the same size. - BitArray myBA1 = new BitArray( 4 ); - BitArray myBA2 = new BitArray( 4 ); - myBA1[0] = myBA1[1] = false; - myBA1[2] = myBA1[3] = true; - myBA2[0] = myBA2[2] = false; - myBA2[1] = myBA2[3] = true; + // Creates and initializes two BitArrays of the same size. + BitArray myBA1 = new(4); + BitArray myBA2 = new(4); + myBA1[0] = myBA1[1] = false; + myBA1[2] = myBA1[3] = true; + myBA2[0] = myBA2[2] = false; + myBA2[1] = myBA2[3] = true; - // Performs a bitwise OR operation between BitArray instances of the same size. - Console.WriteLine( "Initial values" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + // Performs a bitwise OR operation between BitArray instances of the same size. + Console.WriteLine("Initial values"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - Console.WriteLine( "Result" ); - Console.Write( "OR:" ); - PrintValues( myBA1.Or( myBA2 ), 8 ); - Console.WriteLine(); + Console.WriteLine("Result"); + Console.Write("OR:"); + PrintValues(myBA1.Or(myBA2), 8); + Console.WriteLine(); - Console.WriteLine( "After OR" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + Console.WriteLine("After OR"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - // Performing OR between BitArray instances of different sizes returns an exception. - try { - BitArray myBA3 = new BitArray( 8 ); - myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; - myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; - myBA1.Or( myBA3 ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } + // Performing OR between BitArray instances of different sizes returns an exception. + try + { + BitArray myBA3 = new(8); + myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; + myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; + myBA1.Or(myBA3); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myList, int myWidth ) { - int i = myWidth; - foreach ( Object obj in myList ) { - if ( i <= 0 ) { - i = myWidth; - Console.WriteLine(); - } - i--; - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, int myWidth) + { + int i = myWidth; + foreach (object obj in myList) + { + if (i <= 0) + { + i = myWidth; + Console.WriteLine(); + } + i--; + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initial values - myBA1: False False True True - myBA2: False True False True +Initial values +myBA1: False False True True +myBA2: False True False True - Result - OR: False True True True +Result +OR: False True True True - After OR - myBA1: False True True True - myBA2: False True False True +After OR +myBA1: False True True True +myBA2: False True False True - Exception: System.ArgumentException: Array lengths must be the same. - at System.Collections.BitArray.Or(BitArray value) - at SamplesBitArray.Main() - */ +Exception: System.ArgumentException: Array lengths must be the same. + at System.Collections.BitArray.Or(BitArray value) + at SamplesBitArray.Main() +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/Overview/Program.cs b/snippets/csharp/System.Collections/BitArray/Overview/Program.cs new file mode 100644 index 00000000000..ecba6399f07 --- /dev/null +++ b/snippets/csharp/System.Collections/BitArray/Overview/Program.cs @@ -0,0 +1,2 @@ +SamplesBitArray.Run(); +SamplesLocker.Run(); diff --git a/snippets/csharp/System.Collections/BitArray/Overview/Project.csproj b/snippets/csharp/System.Collections/BitArray/Overview/Project.csproj index 192c580d90d..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/BitArray/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/BitArray/Overview/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesBitArray \ No newline at end of file diff --git a/snippets/csharp/System.Collections/BitArray/Overview/source.cs b/snippets/csharp/System.Collections/BitArray/Overview/source.cs index 3b30e1ae7eb..4d5baa0f73d 100644 --- a/snippets/csharp/System.Collections/BitArray/Overview/source.cs +++ b/snippets/csharp/System.Collections/BitArray/Overview/source.cs @@ -1,122 +1,127 @@ // - using System; - using System.Collections; - public class SamplesBitArray { - - public static void Main() { - - // Creates and initializes several BitArrays. - BitArray myBA1 = new BitArray( 5 ); - - BitArray myBA2 = new BitArray( 5, false ); - - byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 }; - BitArray myBA3 = new BitArray( myBytes ); - - bool[] myBools = new bool[5] { true, false, true, true, false }; - BitArray myBA4 = new BitArray( myBools ); - - int[] myInts = new int[5] { 6, 7, 8, 9, 10 }; - BitArray myBA5 = new BitArray( myInts ); - - // Displays the properties and values of the BitArrays. - Console.WriteLine( "myBA1" ); - Console.WriteLine( " Count: {0}", myBA1.Count ); - Console.WriteLine( " Length: {0}", myBA1.Length ); - Console.WriteLine( " Values:" ); - PrintValues( myBA1, 8 ); - - Console.WriteLine( "myBA2" ); - Console.WriteLine( " Count: {0}", myBA2.Count ); - Console.WriteLine( " Length: {0}", myBA2.Length ); - Console.WriteLine( " Values:" ); - PrintValues( myBA2, 8 ); - - Console.WriteLine( "myBA3" ); - Console.WriteLine( " Count: {0}", myBA3.Count ); - Console.WriteLine( " Length: {0}", myBA3.Length ); - Console.WriteLine( " Values:" ); - PrintValues( myBA3, 8 ); - - Console.WriteLine( "myBA4" ); - Console.WriteLine( " Count: {0}", myBA4.Count ); - Console.WriteLine( " Length: {0}", myBA4.Length ); - Console.WriteLine( " Values:" ); - PrintValues( myBA4, 8 ); - - Console.WriteLine( "myBA5" ); - Console.WriteLine( " Count: {0}", myBA5.Count ); - Console.WriteLine( " Length: {0}", myBA5.Length ); - Console.WriteLine( " Values:" ); - PrintValues( myBA5, 8 ); +using System; +using System.Collections; +public class SamplesBitArray +{ + + public static void Run() + { + + // Creates and initializes several BitArrays. + BitArray myBA1 = new(5); + + BitArray myBA2 = new(5, false); + + byte[] myBytes = [1, 2, 3, 4, 5]; + BitArray myBA3 = new(myBytes); + + bool[] myBools = [true, false, true, true, false]; + BitArray myBA4 = new(myBools); + + int[] myInts = [6, 7, 8, 9, 10]; + BitArray myBA5 = new(myInts); + + // Displays the properties and values of the BitArrays. + Console.WriteLine("myBA1"); + Console.WriteLine($" Count: {myBA1.Count}"); + Console.WriteLine($" Length: {myBA1.Length}"); + Console.WriteLine(" Values:"); + PrintValues(myBA1, 8); + + Console.WriteLine("myBA2"); + Console.WriteLine($" Count: {myBA2.Count}"); + Console.WriteLine($" Length: {myBA2.Length}"); + Console.WriteLine(" Values:"); + PrintValues(myBA2, 8); + + Console.WriteLine("myBA3"); + Console.WriteLine($" Count: {myBA3.Count}"); + Console.WriteLine($" Length: {myBA3.Length}"); + Console.WriteLine(" Values:"); + PrintValues(myBA3, 8); + + Console.WriteLine("myBA4"); + Console.WriteLine($" Count: {myBA4.Count}"); + Console.WriteLine($" Length: {myBA4.Length}"); + Console.WriteLine(" Values:"); + PrintValues(myBA4, 8); + + Console.WriteLine("myBA5"); + Console.WriteLine($" Count: {myBA5.Count}"); + Console.WriteLine($" Length: {myBA5.Length}"); + Console.WriteLine(" Values:"); + PrintValues(myBA5, 8); } - public static void PrintValues( IEnumerable myList, int myWidth ) { - int i = myWidth; - foreach ( Object obj in myList ) { - if ( i <= 0 ) { - i = myWidth; - Console.WriteLine(); - } - i--; - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, int myWidth) + { + int i = myWidth; + foreach (object obj in myList) + { + if (i <= 0) + { + i = myWidth; + Console.WriteLine(); + } + i--; + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } - - - /* - This code produces the following output. - - myBA1 - Count: 5 - Length: 5 - Values: - False False False False False - myBA2 - Count: 5 - Length: 5 - Values: - False False False False False - myBA3 - Count: 40 - Length: 40 - Values: - True False False False False False False False - False True False False False False False False - True True False False False False False False - False False True False False False False False - True False True False False False False False - myBA4 - Count: 5 - Length: 5 - Values: - True False True True False - myBA5 - Count: 160 - Length: 160 - Values: - False True True False False False False False - False False False False False False False False - False False False False False False False False - False False False False False False False False - True True True False False False False False - False False False False False False False False - False False False False False False False False - False False False False False False False False - False False False True False False False False - False False False False False False False False - False False False False False False False False - False False False False False False False False - True False False True False False False False - False False False False False False False False - False False False False False False False False - False False False False False False False False - False True False True False False False False - False False False False False False False False - False False False False False False False False - False False False False False False False False - */ +} + + +/* +This code produces the following output. + +myBA1 + Count: 5 + Length: 5 + Values: + False False False False False +myBA2 + Count: 5 + Length: 5 + Values: + False False False False False +myBA3 + Count: 40 + Length: 40 + Values: + True False False False False False False False + False True False False False False False False + True True False False False False False False + False False True False False False False False + True False True False False False False False +myBA4 + Count: 5 + Length: 5 + Values: + True False True True False +myBA5 + Count: 160 + Length: 160 + Values: + False True True False False False False False + False False False False False False False False + False False False False False False False False + False False False False False False False False + True True True False False False False False + False False False False False False False False + False False False False False False False False + False False False False False False False False + False False False True False False False False + False False False False False False False False + False False False False False False False False + False False False False False False False False + True False False True False False False False + False False False False False False False False + False False False False False False False False + False False False False False False False False + False True False True False False False False + False False False False False False False False + False False False False False False False False + False False False False False False False False +*/ // diff --git a/snippets/csharp/System.Collections/BitArray/Overview/source2.cs b/snippets/csharp/System.Collections/BitArray/Overview/source2.cs index 180aef92b12..4ab8321f082 100644 --- a/snippets/csharp/System.Collections/BitArray/Overview/source2.cs +++ b/snippets/csharp/System.Collections/BitArray/Overview/source2.cs @@ -3,12 +3,12 @@ public class SamplesLocker { - public static void Main() + public static void Run() { // - BitArray myCollection = new BitArray(64, true); - lock(myCollection.SyncRoot) + BitArray myCollection = new(64, true); + lock (myCollection.SyncRoot) { foreach (object item in myCollection) { diff --git a/snippets/csharp/System.Collections/BitArray/Xor/source.cs b/snippets/csharp/System.Collections/BitArray/Xor/source.cs index 091ce9fbc24..32a3034a830 100644 --- a/snippets/csharp/System.Collections/BitArray/Xor/source.cs +++ b/snippets/csharp/System.Collections/BitArray/Xor/source.cs @@ -1,81 +1,89 @@ // - using System; - using System.Collections; - public class SamplesBitArray { +using System; +using System.Collections; +public class SamplesBitArray +{ - public static void Main() { + public static void Main() + { - // Creates and initializes two BitArrays of the same size. - BitArray myBA1 = new BitArray( 4 ); - BitArray myBA2 = new BitArray( 4 ); - myBA1[0] = myBA1[1] = false; - myBA1[2] = myBA1[3] = true; - myBA2[0] = myBA2[2] = false; - myBA2[1] = myBA2[3] = true; + // Creates and initializes two BitArrays of the same size. + BitArray myBA1 = new(4); + BitArray myBA2 = new(4); + myBA1[0] = myBA1[1] = false; + myBA1[2] = myBA1[3] = true; + myBA2[0] = myBA2[2] = false; + myBA2[1] = myBA2[3] = true; - // Performs a bitwise XOR operation between BitArray instances of the same size. - Console.WriteLine( "Initial values" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + // Performs a bitwise XOR operation between BitArray instances of the same size. + Console.WriteLine("Initial values"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - Console.WriteLine( "Result" ); - Console.Write( "XOR:" ); - PrintValues( myBA1.Xor( myBA2 ), 8 ); - Console.WriteLine(); + Console.WriteLine("Result"); + Console.Write("XOR:"); + PrintValues(myBA1.Xor(myBA2), 8); + Console.WriteLine(); - Console.WriteLine( "After XOR" ); - Console.Write( "myBA1:" ); - PrintValues( myBA1, 8 ); - Console.Write( "myBA2:" ); - PrintValues( myBA2, 8 ); - Console.WriteLine(); + Console.WriteLine("After XOR"); + Console.Write("myBA1:"); + PrintValues(myBA1, 8); + Console.Write("myBA2:"); + PrintValues(myBA2, 8); + Console.WriteLine(); - // Performing XOR between BitArray instances of different sizes returns an exception. - try { - BitArray myBA3 = new BitArray( 8 ); - myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; - myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; - myBA1.Xor( myBA3 ); - } catch ( Exception myException ) { - Console.WriteLine("Exception: " + myException.ToString()); - } + // Performing XOR between BitArray instances of different sizes returns an exception. + try + { + BitArray myBA3 = new(8); + myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false; + myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true; + myBA1.Xor(myBA3); + } + catch (Exception myException) + { + Console.WriteLine($"Exception: {myException}"); + } } - public static void PrintValues( IEnumerable myList, int myWidth ) { - int i = myWidth; - foreach ( Object obj in myList ) { - if ( i <= 0 ) { - i = myWidth; - Console.WriteLine(); - } - i--; - Console.Write( "{0,8}", obj ); - } - Console.WriteLine(); + public static void PrintValues(IEnumerable myList, int myWidth) + { + int i = myWidth; + foreach (object obj in myList) + { + if (i <= 0) + { + i = myWidth; + Console.WriteLine(); + } + i--; + Console.Write($"{obj,8}"); + } + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initial values - myBA1: False False True True - myBA2: False True False True +Initial values +myBA1: False False True True +myBA2: False True False True - Result - XOR: False True True False +Result +XOR: False True True False - After XOR - myBA1: False True True False - myBA2: False True False True +After XOR +myBA1: False True True False +myBA2: False True False True - Exception: System.ArgumentException: Array lengths must be the same. - at System.Collections.BitArray.Xor(BitArray value) - at SamplesBitArray.Main() +Exception: System.ArgumentException: Array lengths must be the same. + at System.Collections.BitArray.Xor(BitArray value) + at SamplesBitArray.Main() - */ +*/ // diff --git a/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/Project.csproj b/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/caseinsensitive.cs b/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/caseinsensitive.cs index 2a2a024b32e..e0fe25429b3 100644 --- a/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/caseinsensitive.cs +++ b/snippets/csharp/System.Collections/CaseInsensitiveComparer/Overview/caseinsensitive.cs @@ -6,44 +6,54 @@ using System.Collections; using System.Globalization; -public class SamplesHashtable { - - public static void Main() { - - // Create a Hashtable using the default hash code provider and the default comparer. - Hashtable myHT1 = new Hashtable(); - myHT1.Add("FIRST", "Hello"); - myHT1.Add("SECOND", "World"); - myHT1.Add("THIRD", "!"); - - // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, - // based on the culture of the current thread. - Hashtable myHT2 = new Hashtable( new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer() ); - myHT2.Add("FIRST", "Hello"); - myHT2.Add("SECOND", "World"); - myHT2.Add("THIRD", "!"); - - // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, - // based on the InvariantCulture. - Hashtable myHT3 = new Hashtable( CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant ); - myHT3.Add("FIRST", "Hello"); - myHT3.Add("SECOND", "World"); - myHT3.Add("THIRD", "!"); - - // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, - // based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i". - CultureInfo myCul = new CultureInfo( "tr-TR" ); - Hashtable myHT4 = new Hashtable( new CaseInsensitiveHashCodeProvider( myCul ), new CaseInsensitiveComparer( myCul ) ); - myHT4.Add("FIRST", "Hello"); - myHT4.Add("SECOND", "World"); - myHT4.Add("THIRD", "!"); - - // Search for a key in each hashtable. - Console.WriteLine( "first is in myHT1: {0}", myHT1.ContainsKey( "first" ) ); - Console.WriteLine( "first is in myHT2: {0}", myHT2.ContainsKey( "first" ) ); - Console.WriteLine( "first is in myHT3: {0}", myHT3.ContainsKey( "first" ) ); - Console.WriteLine( "first is in myHT4: {0}", myHT4.ContainsKey( "first" ) ); - } +public class SamplesHashtable +{ + + public static void Main() + { + + // Create a Hashtable using the default hash code provider and the default comparer. + Hashtable myHT1 = new() + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; + + // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, + // based on the culture of the current thread. + Hashtable myHT2 = new(new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer()) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; + + // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, + // based on the InvariantCulture. + Hashtable myHT3 = new(CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; + + // Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer, + // based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i". + CultureInfo myCul = new("tr-TR"); + Hashtable myHT4 = new(new CaseInsensitiveHashCodeProvider(myCul), new CaseInsensitiveComparer(myCul)) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; + + // Search for a key in each hashtable. + Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}"); + } } diff --git a/snippets/csharp/System.Collections/CollectionBase/Overview/Program.cs b/snippets/csharp/System.Collections/CollectionBase/Overview/Program.cs new file mode 100644 index 00000000000..22b339b3118 --- /dev/null +++ b/snippets/csharp/System.Collections/CollectionBase/Overview/Program.cs @@ -0,0 +1,2 @@ +SamplesCollectionBase.Run(); +SamplesSynchronizedCollectionBase.Run(); diff --git a/snippets/csharp/System.Collections/CollectionBase/Overview/Project.csproj b/snippets/csharp/System.Collections/CollectionBase/Overview/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/CollectionBase/Overview/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/CollectionBase/Overview/collectionbase.cs b/snippets/csharp/System.Collections/CollectionBase/Overview/collectionbase.cs index 62c010e7d91..436c7b5d4ac 100644 --- a/snippets/csharp/System.Collections/CollectionBase/Overview/collectionbase.cs +++ b/snippets/csharp/System.Collections/CollectionBase/Overview/collectionbase.cs @@ -1,131 +1,140 @@ -// The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects. +// The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects. // using System; using System.Collections; -public class Int16Collection : CollectionBase { - - public Int16 this[ int index ] { - get { - return( (Int16) List[index] ); - } - set { - List[index] = value; - } - } - - public int Add( Int16 value ) { - return( List.Add( value ) ); - } - - public int IndexOf( Int16 value ) { - return( List.IndexOf( value ) ); - } - - public void Insert( int index, Int16 value ) { - List.Insert( index, value ); - } - - public void Remove( Int16 value ) { - List.Remove( value ); - } - - public bool Contains( Int16 value ) { - // If value is not of type Int16, this will return false. - return( List.Contains( value ) ); - } - - protected override void OnInsert( int index, Object value ) { - // Insert additional code to be run only when inserting values. - } - - protected override void OnRemove( int index, Object value ) { - // Insert additional code to be run only when removing values. - } - - protected override void OnSet( int index, Object oldValue, Object newValue ) { - // Insert additional code to be run only when setting values. - } - - protected override void OnValidate( Object value ) { - if ( value.GetType() != typeof(System.Int16) ) - throw new ArgumentException( "value must be of type Int16.", "value" ); - } +public class Int16Collection : CollectionBase +{ + + public short this[int index] + { + get => ((short)List[index]); set => List[index] = value; + } + + public int Add(short value) => (List.Add(value)); + + public int IndexOf(short value) => (List.IndexOf(value)); + + public void Insert(int index, short value) => List.Insert(index, value); + + public void Remove(short value) => List.Remove(value); + + public bool Contains(short value) => + // If value isn't of type Int16, this returns false. + (List.Contains(value)); + + protected override void OnInsert(int index, object value) + { + // Insert additional code to be run only when inserting values. + } + + protected override void OnRemove(int index, object value) + { + // Insert additional code to be run only when removing values. + } + + protected override void OnSet(int index, object oldValue, object newValue) + { + // Insert additional code to be run only when setting values. + } + + protected override void OnValidate(object value) + { + if (value.GetType() != typeof(short)) + { + throw new ArgumentException("value must be of type Int16.", "value"); + } + } } -public class SamplesCollectionBase { - - public static void Main() { - - // Create and initialize a new CollectionBase. - Int16Collection myI16 = new Int16Collection(); - - // Add elements to the collection. - myI16.Add( (Int16) 1 ); - myI16.Add( (Int16) 2 ); - myI16.Add( (Int16) 3 ); - myI16.Add( (Int16) 5 ); - myI16.Add( (Int16) 7 ); - - // Display the contents of the collection using foreach. This is the preferred method. - Console.WriteLine( "Contents of the collection (using foreach):" ); - PrintValues1( myI16 ); - - // Display the contents of the collection using the enumerator. - Console.WriteLine( "Contents of the collection (using enumerator):" ); - PrintValues2( myI16 ); - - // Display the contents of the collection using the Count property and the Item property. - Console.WriteLine( "Initial contents of the collection (using Count and Item):" ); - PrintIndexAndValues( myI16 ); - - // Search the collection with Contains and IndexOf. - Console.WriteLine( "Contains 3: {0}", myI16.Contains( 3 ) ); - Console.WriteLine( "2 is at index {0}.", myI16.IndexOf( 2 ) ); - Console.WriteLine(); - - // Insert an element into the collection at index 3. - myI16.Insert( 3, (Int16) 13 ); - Console.WriteLine( "Contents of the collection after inserting at index 3:" ); - PrintIndexAndValues( myI16 ); - - // Get and set an element using the index. - myI16[4] = 123; - Console.WriteLine( "Contents of the collection after setting the element at index 4 to 123:" ); - PrintIndexAndValues( myI16 ); - - // Remove an element from the collection. - myI16.Remove( (Int16) 2 ); - - // Display the contents of the collection using the Count property and the Item property. - Console.WriteLine( "Contents of the collection after removing the element 2:" ); - PrintIndexAndValues( myI16 ); - } - - // Uses the Count property and the Item property. - public static void PrintIndexAndValues( Int16Collection myCol ) { - for ( int i = 0; i < myCol.Count; i++ ) - Console.WriteLine( " [{0}]: {1}", i, myCol[i] ); - Console.WriteLine(); - } - - // Uses the foreach statement which hides the complexity of the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintValues1( Int16Collection myCol ) { - foreach ( Int16 i16 in myCol ) - Console.WriteLine( " {0}", i16 ); - Console.WriteLine(); - } - - // Uses the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintValues2( Int16Collection myCol ) { - System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); - while ( myEnumerator.MoveNext() ) - Console.WriteLine( " {0}", myEnumerator.Current ); - Console.WriteLine(); - } +public class SamplesCollectionBase +{ + + public static void Run() + { + + // Create and initialize a new CollectionBase. + Int16Collection myI16 = + [ + // Add elements to the collection. + (short)1, + (short)2, + (short)3, + (short)5, + (short)7, + ]; + + // Display the contents of the collection using foreach. This is the preferred method. + Console.WriteLine("Contents of the collection (using foreach):"); + PrintValues1(myI16); + + // Display the contents of the collection using the enumerator. + Console.WriteLine("Contents of the collection (using enumerator):"); + PrintValues2(myI16); + + // Display the contents of the collection using the Count property and the Item property. + Console.WriteLine("Initial contents of the collection (using Count and Item):"); + PrintIndexAndValues(myI16); + + // Search the collection with Contains and IndexOf. + Console.WriteLine($"Contains 3: {myI16.Contains(3)}"); + Console.WriteLine($"2 is at index {myI16.IndexOf(2)}."); + Console.WriteLine(); + + // Insert an element into the collection at index 3. + myI16.Insert(3, (short)13); + Console.WriteLine("Contents of the collection after inserting at index 3:"); + PrintIndexAndValues(myI16); + + // Get and set an element using the index. + myI16[4] = 123; + Console.WriteLine("Contents of the collection after setting the element at index 4 to 123:"); + PrintIndexAndValues(myI16); + + // Remove an element from the collection. + myI16.Remove((short)2); + + // Display the contents of the collection using the Count property and the Item property. + Console.WriteLine("Contents of the collection after removing the element 2:"); + PrintIndexAndValues(myI16); + } + + // Uses the Count property and the Item property. + public static void PrintIndexAndValues(Int16Collection myCol) + { + for (int i = 0; i < myCol.Count; i++) + { + Console.WriteLine($" [{i}]: {myCol[i]}"); + } + + Console.WriteLine(); + } + + // Uses the foreach statement which hides the complexity of the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintValues1(Int16Collection myCol) + { + foreach (short i16 in myCol) + { + Console.WriteLine($" {i16}"); + } + + Console.WriteLine(); + } + + // Uses the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintValues2(Int16Collection myCol) + { + System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); + while (myEnumerator.MoveNext()) + { + Console.WriteLine($" {myEnumerator.Current}"); + } + + Console.WriteLine(); + } } diff --git a/snippets/csharp/System.Collections/CollectionBase/Overview/remarks.cs b/snippets/csharp/System.Collections/CollectionBase/Overview/remarks.cs index 1b012f50143..e4b14a19a65 100644 --- a/snippets/csharp/System.Collections/CollectionBase/Overview/remarks.cs +++ b/snippets/csharp/System.Collections/CollectionBase/Overview/remarks.cs @@ -1,77 +1,72 @@ -// The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects. +// The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects. using System; using System.Collections; -public class Int16Collection : CollectionBase { +public class SynchronizedInt16Collection : CollectionBase +{ - public Int16 this[ int index ] { - get { - return( (Int16) List[index] ); - } - set { - List[index] = value; - } - } + public short this[int index] + { + get => ((short)List[index]); set => List[index] = value; + } - public int Add( Int16 value ) { - return( List.Add( value ) ); - } + public int Add(short value) => (List.Add(value)); - public int IndexOf( Int16 value ) { - return( List.IndexOf( value ) ); - } + public int IndexOf(short value) => (List.IndexOf(value)); - public void Insert( int index, Int16 value ) { - List.Insert( index, value ); - } + public void Insert(int index, short value) => List.Insert(index, value); - public void Remove( Int16 value ) { - List.Remove( value ); - } + public void Remove(short value) => List.Remove(value); - public bool Contains( Int16 value ) { - // If value is not of type Int16, this will return false. - return( List.Contains( value ) ); - } + public bool Contains(short value) => + // If value isn't of type Int16, this returns false. + (List.Contains(value)); - protected override void OnInsert( int index, Object value ) { - // Insert additional code to be run only when inserting values. - } + protected override void OnInsert(int index, object value) + { + // Insert additional code to be run only when inserting values. + } - protected override void OnRemove( int index, Object value ) { - // Insert additional code to be run only when removing values. - } + protected override void OnRemove(int index, object value) + { + // Insert additional code to be run only when removing values. + } - protected override void OnSet( int index, Object oldValue, Object newValue ) { - // Insert additional code to be run only when setting values. - } + protected override void OnSet(int index, object oldValue, object newValue) + { + // Insert additional code to be run only when setting values. + } - protected override void OnValidate( Object value ) { - if ( value.GetType() != typeof(System.Int16) ) - throw new ArgumentException( "value must be of type Int16.", "value" ); - } + protected override void OnValidate(object value) + { + if (value.GetType() != typeof(short)) + { + throw new ArgumentException("value must be of type Int16.", "value"); + } + } } -public class SamplesCollectionBase +public class SamplesSynchronizedCollectionBase { - public static void Main() + public static void Run() { // Create and initialize a new CollectionBase. - Int16Collection myCollectionBase = new Int16Collection(); - - // Add elements to the collection. - myCollectionBase.Add( (Int16) 1 ); - myCollectionBase.Add( (Int16) 2 ); - myCollectionBase.Add( (Int16) 3 ); - myCollectionBase.Add( (Int16) 5 ); - myCollectionBase.Add( (Int16) 7 ); + SynchronizedInt16Collection myCollectionBase = + [ + // Add elements to the collection. + (short)1, + (short)2, + (short)3, + (short)5, + (short)7, + ]; // // Get the ICollection interface from the CollectionBase // derived class. ICollection myCollection = myCollectionBase; - lock(myCollection.SyncRoot) + lock (myCollection.SyncRoot) { foreach (object item in myCollection) { @@ -80,4 +75,4 @@ public static void Main() } // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System.Collections/Comparer/Overview/Project.csproj b/snippets/csharp/System.Collections/Comparer/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/Comparer/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/Comparer/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/Comparer/Overview/comparercultures.cs b/snippets/csharp/System.Collections/Comparer/Overview/comparercultures.cs index 43495ba22f9..83a13a3a97f 100644 --- a/snippets/csharp/System.Collections/Comparer/Overview/comparercultures.cs +++ b/snippets/csharp/System.Collections/Comparer/Overview/comparercultures.cs @@ -5,26 +5,28 @@ using System.Collections; using System.Globalization; -public class SamplesComparer { +public class SamplesComparer +{ - public static void Main() { + public static void Main() + { - // Creates the strings to compare. - String str1 = "llegar"; - String str2 = "lugar"; - Console.WriteLine( "Comparing \"{0}\" and \"{1}\" ...", str1, str2 ); + // Creates the strings to compare. + string str1 = "llegar"; + string str2 = "lugar"; + Console.WriteLine($"Comparing \"{str1}\" and \"{str2}\" ..."); - // Uses the DefaultInvariant Comparer. - Console.WriteLine( " Invariant Comparer: {0}", Comparer.DefaultInvariant.Compare( str1, str2 ) ); + // Uses the DefaultInvariant Comparer. + Console.WriteLine($" Invariant Comparer: {Comparer.DefaultInvariant.Compare(str1, str2)}"); - // Uses the Comparer based on the culture "es-ES" (Spanish - Spain, international sort). - Comparer myCompIntl = new Comparer( new CultureInfo( "es-ES", false ) ); - Console.WriteLine( " International Sort: {0}", myCompIntl.Compare( str1, str2 ) ); + // Uses the Comparer based on the culture "es-ES" (Spanish - Spain, international sort). + Comparer myCompIntl = new(new CultureInfo("es-ES", false)); + Console.WriteLine($" International Sort: {myCompIntl.Compare(str1, str2)}"); - // Uses the Comparer based on the culture identifier 0x040A (Spanish - Spain, traditional sort). - Comparer myCompTrad = new Comparer( new CultureInfo( 0x040A, false ) ); - Console.WriteLine( " Traditional Sort : {0}", myCompTrad.Compare( str1, str2 ) ); - } + // Uses the Comparer based on the culture identifier 0x040A (Spanish - Spain, traditional sort). + Comparer myCompTrad = new(new CultureInfo(0x040A, false)); + Console.WriteLine($" Traditional Sort : {myCompTrad.Compare(str1, str2)}"); + } } /* diff --git a/snippets/csharp/System.Collections/DictionaryBase/Overview/Program.cs b/snippets/csharp/System.Collections/DictionaryBase/Overview/Program.cs new file mode 100644 index 00000000000..d9970da1497 --- /dev/null +++ b/snippets/csharp/System.Collections/DictionaryBase/Overview/Program.cs @@ -0,0 +1,2 @@ +SamplesDictionaryBase.Run(); +SamplesSynchronizedDictionaryBase.Run(); diff --git a/snippets/csharp/System.Collections/DictionaryBase/Overview/Project.csproj b/snippets/csharp/System.Collections/DictionaryBase/Overview/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/DictionaryBase/Overview/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/DictionaryBase/Overview/dictionarybase.cs b/snippets/csharp/System.Collections/DictionaryBase/Overview/dictionarybase.cs index 17668afa00a..1f00b5938fe 100644 --- a/snippets/csharp/System.Collections/DictionaryBase/Overview/dictionarybase.cs +++ b/snippets/csharp/System.Collections/DictionaryBase/Overview/dictionarybase.cs @@ -1,208 +1,236 @@ -// The following code example implements the DictionaryBase class and uses that implementation to create a dictionary of String keys and values that have a Length of 5 or less. +// The following code example implements the DictionaryBase class and uses that implementation to create a dictionary of string keys and values that have a Length of 5 or less. // using System; using System.Collections; -public class ShortStringDictionary : DictionaryBase { +public class ShortStringDictionary : DictionaryBase +{ - public String this[ String key ] { - get { - return( (String) Dictionary[key] ); - } - set { - Dictionary[key] = value; - } - } + public string this[string key] + { + get => ((string)Dictionary[key]); set => Dictionary[key] = value; + } - public ICollection Keys { - get { - return( Dictionary.Keys ); - } - } + public ICollection Keys => (Dictionary.Keys); - public ICollection Values { - get { - return( Dictionary.Values ); - } - } + public ICollection Values => (Dictionary.Values); - public void Add( String key, String value ) { - Dictionary.Add( key, value ); - } + public void Add(string key, string value) => Dictionary.Add(key, value); - public bool Contains( String key ) { - return( Dictionary.Contains( key ) ); - } + public bool Contains(string key) => (Dictionary.Contains(key)); - public void Remove( String key ) { - Dictionary.Remove( key ); - } + public void Remove(string key) => Dictionary.Remove(key); - protected override void OnInsert( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) + protected override void OnInsert(object key, object value) + { + if (key.GetType() != typeof(string)) { - throw new ArgumentException( "key must be of type String.", "key" ); + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - if ( value.GetType() != typeof(System.String) ) + if (value.GetType() != typeof(string)) + { + throw new ArgumentException("value must be of type string.", "value"); + } + else { - throw new ArgumentException( "value must be of type String.", "value" ); + string strValue = (string)value; + if (strValue.Length > 5) + { + throw new ArgumentException("value must be no more than 5 characters in length.", "value"); + } } - else { - String strValue = (String) value; - if ( strValue.Length > 5 ) - throw new ArgumentException( "value must be no more than 5 characters in length.", "value" ); - } - } + } - protected override void OnRemove( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) + protected override void OnRemove(object key, object value) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else { - throw new ArgumentException( "key must be of type String.", "key" ); + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - } + } - protected override void OnSet( Object key, Object oldValue, Object newValue ) { - if ( key.GetType() != typeof(System.String) ) + protected override void OnSet(object key, object oldValue, object newValue) + { + if (key.GetType() != typeof(string)) { - throw new ArgumentException( "key must be of type String.", "key" ); + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - if ( newValue.GetType() != typeof(System.String) ) + if (newValue.GetType() != typeof(string)) { - throw new ArgumentException( "newValue must be of type String.", "newValue" ); + throw new ArgumentException("newValue must be of type string.", "newValue"); } - else { - String strValue = (String) newValue; - if ( strValue.Length > 5 ) - throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" ); - } - } + else + { + string strValue = (string)newValue; + if (strValue.Length > 5) + { + throw new ArgumentException("newValue must be no more than 5 characters in length.", "newValue"); + } + } + } - protected override void OnValidate( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) + protected override void OnValidate(object key, object value) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else { - throw new ArgumentException( "key must be of type String.", "key" ); + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - if ( value.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "value must be of type String.", "value" ); + if (value.GetType() != typeof(string)) + { + throw new ArgumentException("value must be of type string.", "value"); + } + else + { + string strValue = (string)value; + if (strValue.Length > 5) + { + throw new ArgumentException("value must be no more than 5 characters in length.", "value"); + } } - else { - String strValue = (String) value; - if ( strValue.Length > 5 ) - throw new ArgumentException( "value must be no more than 5 characters in length.", "value" ); - } - } + } } -public class SamplesDictionaryBase { - - public static void Main() { - - // Creates and initializes a new DictionaryBase. - ShortStringDictionary mySSC = new ShortStringDictionary(); - - // Adds elements to the collection. - mySSC.Add( "One", "a" ); - mySSC.Add( "Two", "ab" ); - mySSC.Add( "Three", "abc" ); - mySSC.Add( "Four", "abcd" ); - mySSC.Add( "Five", "abcde" ); - - // Display the contents of the collection using foreach. This is the preferred method. - Console.WriteLine( "Contents of the collection (using foreach):" ); - PrintKeysAndValues1( mySSC ); - - // Display the contents of the collection using the enumerator. - Console.WriteLine( "Contents of the collection (using enumerator):" ); - PrintKeysAndValues2( mySSC ); - - // Display the contents of the collection using the Keys property and the Item property. - Console.WriteLine( "Initial contents of the collection (using Keys and Item):" ); - PrintKeysAndValues3( mySSC ); - - // Tries to add a value that is too long. - try { - mySSC.Add( "Ten", "abcdefghij" ); - } - catch ( ArgumentException e ) { - Console.WriteLine( e.ToString() ); - } - - // Tries to add a key that is too long. - try { - mySSC.Add( "Eleven", "ijk" ); - } - catch ( ArgumentException e ) { - Console.WriteLine( e.ToString() ); - } - - Console.WriteLine(); - - // Searches the collection with Contains. - Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) ); - Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) ); - Console.WriteLine(); - - // Removes an element from the collection. - mySSC.Remove( "Two" ); - - // Displays the contents of the collection. - Console.WriteLine( "After removing \"Two\":" ); - PrintKeysAndValues1( mySSC ); - } - - // Uses the foreach statement which hides the complexity of the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintKeysAndValues1( ShortStringDictionary myCol ) { - foreach ( DictionaryEntry myDE in myCol ) - Console.WriteLine( " {0,-5} : {1}", myDE.Key, myDE.Value ); - Console.WriteLine(); - } - - // Uses the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintKeysAndValues2( ShortStringDictionary myCol ) { - DictionaryEntry myDE; - System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); - while ( myEnumerator.MoveNext() ) - if ( myEnumerator.Current != null ) { - myDE = (DictionaryEntry) myEnumerator.Current; - Console.WriteLine( " {0,-5} : {1}", myDE.Key, myDE.Value ); - } - Console.WriteLine(); - } - - // Uses the Keys property and the Item property. - public static void PrintKeysAndValues3( ShortStringDictionary myCol ) { - ICollection myKeys = myCol.Keys; - foreach ( String k in myKeys ) - Console.WriteLine( " {0,-5} : {1}", k, myCol[k] ); - Console.WriteLine(); - } +public class SamplesDictionaryBase +{ + + public static void Run() + { + + // Creates and initializes a new DictionaryBase. + ShortStringDictionary mySSC = new() + { + // Adds elements to the collection. + { "One", "a" }, + { "Two", "ab" }, + { "Three", "abc" }, + { "Four", "abcd" }, + { "Five", "abcde" } + }; + + // Display the contents of the collection using foreach. This is the preferred method. + Console.WriteLine("Contents of the collection (using foreach):"); + PrintKeysAndValues1(mySSC); + + // Display the contents of the collection using the enumerator. + Console.WriteLine("Contents of the collection (using enumerator):"); + PrintKeysAndValues2(mySSC); + + // Display the contents of the collection using the Keys property and the Item property. + Console.WriteLine("Initial contents of the collection (using Keys and Item):"); + PrintKeysAndValues3(mySSC); + + // Tries to add a value that is too long. + try + { + mySSC.Add("Ten", "abcdefghij"); + } + catch (ArgumentException e) + { + Console.WriteLine(e); + } + + // Tries to add a key that is too long. + try + { + mySSC.Add("Eleven", "ijk"); + } + catch (ArgumentException e) + { + Console.WriteLine(e); + } + + Console.WriteLine(); + + // Searches the collection with Contains. + Console.WriteLine($"Contains \"Three\": {mySSC.Contains("Three")}"); + Console.WriteLine($"Contains \"Twelve\": {mySSC.Contains("Twelve")}"); + Console.WriteLine(); + + // Removes an element from the collection. + mySSC.Remove("Two"); + + // Displays the contents of the collection. + Console.WriteLine("After removing \"Two\":"); + PrintKeysAndValues1(mySSC); + } + + // Uses the foreach statement which hides the complexity of the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintKeysAndValues1(ShortStringDictionary myCol) + { + foreach (DictionaryEntry myDE in myCol) + { + Console.WriteLine($" {myDE.Key,-5} : {myDE.Value}"); + } + + Console.WriteLine(); + } + + // Uses the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintKeysAndValues2(ShortStringDictionary myCol) + { + DictionaryEntry myDE; + System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); + while (myEnumerator.MoveNext()) + { + if (myEnumerator.Current != null) + { + myDE = (DictionaryEntry)myEnumerator.Current; + Console.WriteLine($" {myDE.Key,-5} : {myDE.Value}"); + } + } + + Console.WriteLine(); + } + + // Uses the Keys property and the Item property. + public static void PrintKeysAndValues3(ShortStringDictionary myCol) + { + ICollection myKeys = myCol.Keys; + foreach (string k in myKeys) + { + Console.WriteLine($" {k,-5} : {myCol[k]}"); + } + + Console.WriteLine(); + } } @@ -232,13 +260,13 @@ Initial contents of the collection (using Keys and Item): System.ArgumentException: value must be no more than 5 characters in length. Parameter name: value - at ShortStringDictionary.OnValidate(Object key, Object value) - at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value) + at ShortStringDictionary.OnValidate(object key, object value) + at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(object key, object value) at SamplesDictionaryBase.Main() System.ArgumentException: key must be no more than 5 characters in length. Parameter name: key - at ShortStringDictionary.OnValidate(Object key, Object value) - at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value) + at ShortStringDictionary.OnValidate(object key, object value) + at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(object key, object value) at SamplesDictionaryBase.Main() Contains "Three": True diff --git a/snippets/csharp/System.Collections/DictionaryBase/Overview/source2.cs b/snippets/csharp/System.Collections/DictionaryBase/Overview/source2.cs index 64ffbdcb771..5654c0b98dd 100644 --- a/snippets/csharp/System.Collections/DictionaryBase/Overview/source2.cs +++ b/snippets/csharp/System.Collections/DictionaryBase/Overview/source2.cs @@ -1,125 +1,133 @@ using System; using System.Collections; -public class ShortStringDictionary : DictionaryBase { +public class SynchronizedShortStringDictionary : DictionaryBase +{ + + public string this[string key] + { + get => ((string)Dictionary[key]); set => Dictionary[key] = value; + } + + public ICollection Keys => (Dictionary.Keys); + + public ICollection Values => (Dictionary.Values); + + public void Add(string key, string value) => Dictionary.Add(key, value); + + public bool Contains(string key) => (Dictionary.Contains(key)); + + public void Remove(string key) => Dictionary.Remove(key); + + protected override void OnInsert(object key, object value) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } + } + + if (value.GetType() != typeof(string)) + { + throw new ArgumentException("value must be of type string.", "value"); + } + else + { + string strValue = (string)value; + if (strValue.Length > 5) + { + throw new ArgumentException("value must be no more than 5 characters in length.", "value"); + } + } + } + + protected override void OnRemove(object key, object value) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } + } + } - public String this[ String key ] { - get { - return( (String) Dictionary[key] ); - } - set { - Dictionary[key] = value; - } - } + protected override void OnSet(object key, object oldValue, object newValue) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } + } - public ICollection Keys { - get { - return( Dictionary.Keys ); - } - } - - public ICollection Values { - get { - return( Dictionary.Values ); - } - } - - public void Add( String key, String value ) { - Dictionary.Add( key, value ); - } - - public bool Contains( String key ) { - return( Dictionary.Contains( key ) ); - } - - public void Remove( String key ) { - Dictionary.Remove( key ); - } - - protected override void OnInsert( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "key must be of type String.", "key" ); - } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - - if ( value.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "value must be of type String.", "value" ); - } - else { - String strValue = (String) value; - if ( strValue.Length > 5 ) - throw new ArgumentException( "value must be no more than 5 characters in length.", "value" ); - } - } - - protected override void OnRemove( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "key must be of type String.", "key" ); - } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - } - - protected override void OnSet( Object key, Object oldValue, Object newValue ) { - if ( key.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "key must be of type String.", "key" ); - } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } - - if ( newValue.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "newValue must be of type String.", "newValue" ); - } - else { - String strValue = (String) newValue; - if ( strValue.Length > 5 ) - throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" ); - } - } - - protected override void OnValidate( Object key, Object value ) { - if ( key.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "key must be of type String.", "key" ); - } - else { - String strKey = (String) key; - if ( strKey.Length > 5 ) - throw new ArgumentException( "key must be no more than 5 characters in length.", "key" ); - } + if (newValue.GetType() != typeof(string)) + { + throw new ArgumentException("newValue must be of type string.", "newValue"); + } + else + { + string strValue = (string)newValue; + if (strValue.Length > 5) + { + throw new ArgumentException("newValue must be no more than 5 characters in length.", "newValue"); + } + } + } - if ( value.GetType() != typeof(System.String) ) - { - throw new ArgumentException( "value must be of type String.", "value" ); + protected override void OnValidate(object key, object value) + { + if (key.GetType() != typeof(string)) + { + throw new ArgumentException("key must be of type string.", "key"); + } + else + { + string strKey = (string)key; + if (strKey.Length > 5) + { + throw new ArgumentException("key must be no more than 5 characters in length.", "key"); + } } - else { - String strValue = (String) value; - if ( strValue.Length > 5 ) - throw new ArgumentException( "value must be no more than 5 characters in length.", "value" ); - } - } + + if (value.GetType() != typeof(string)) + { + throw new ArgumentException("value must be of type string.", "value"); + } + else + { + string strValue = (string)value; + if (strValue.Length > 5) + { + throw new ArgumentException("value must be no more than 5 characters in length.", "value"); + } + } + } } -public class SamplesDictionaryBase +public class SamplesSynchronizedDictionaryBase { - public static void Main() + public static void Run() { - DictionaryBase myDictionary = new ShortStringDictionary(); + DictionaryBase myDictionary = new SynchronizedShortStringDictionary(); // foreach (DictionaryEntry de in myDictionary) @@ -129,10 +137,10 @@ public static void Main() // // - ICollection myCollection = new ShortStringDictionary(); - lock(myCollection.SyncRoot) + ICollection myCollection = new SynchronizedShortStringDictionary(); + lock (myCollection.SyncRoot) { - foreach (Object item in myCollection) + foreach (object item in myCollection) { // Insert your code here. } diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Key/Dictionary.cs b/snippets/csharp/System.Collections/DictionaryEntry/Key/Dictionary.cs index 3b2bb3a8b6d..5bc73072b38 100644 --- a/snippets/csharp/System.Collections/DictionaryEntry/Key/Dictionary.cs +++ b/snippets/csharp/System.Collections/DictionaryEntry/Key/Dictionary.cs @@ -9,42 +9,41 @@ // This class implements a simple dictionary using an array of DictionaryEntry objects (key/value pairs). public class SimpleDictionary : IDictionary { - // The array of items + // The array of items. private DictionaryEntry[] items; - private Int32 ItemsInUse = 0; // Construct the SimpleDictionary with the desired number of items. // The number of items cannot change for the life time of this SimpleDictionary. - public SimpleDictionary(Int32 numItems) - { - items = new DictionaryEntry[numItems]; - } + public SimpleDictionary(int numItems) => items = new DictionaryEntry[numItems]; #region IDictionary Members // - public bool IsReadOnly { get { return false; } } + public bool IsReadOnly => false; // // public bool Contains(object key) { - Int32 index; - return TryGetIndexOfKey(key, out index); + int index; + return TryGetIndexOfKey(key, out index); } // // - public bool IsFixedSize { get { return false; } } + public bool IsFixedSize => false; // // public void Remove(object key) { - if (key == null) throw new ArgumentNullException("key"); - // Try to find the key in the DictionaryEntry array - Int32 index; + if (key == null) + { + throw new ArgumentNullException("key"); + } + // Try to find the key in the DictionaryEntry array. + int index; if (TryGetIndexOfKey(key, out index)) { // If the key is found, slide all the items up. - Array.Copy(items, index + 1, items, index, ItemsInUse - index - 1); - ItemsInUse--; + Array.Copy(items, index + 1, items, index, Count - index - 1); + Count--; } else { @@ -53,15 +52,18 @@ public void Remove(object key) } // // - public void Clear() { ItemsInUse = 0; } + public void Clear() => Count = 0; // // public void Add(object key, object value) { // Add the new key/value pair even if this key already exists in the dictionary. - if (ItemsInUse == items.Length) + if (Count == items.Length) + { throw new InvalidOperationException("The dictionary cannot hold any more items."); - items[ItemsInUse++] = new DictionaryEntry(key, value); + } + + items[Count++] = new(key, value); } // // @@ -70,9 +72,12 @@ public ICollection Keys get { // Return an array where each item is a key. - Object[] keys = new Object[ItemsInUse]; - for (Int32 n = 0; n < ItemsInUse; n++) + object[] keys = new object[Count]; + for (int n = 0; n < Count; n++) + { keys[n] = items[n].Key; + } + return keys; } } @@ -83,9 +88,12 @@ public ICollection Values get { // Return an array where each item is a value. - Object[] values = new Object[ItemsInUse]; - for (Int32 n = 0; n < ItemsInUse; n++) + object[] values = new object[Count]; + for (int n = 0; n < Count; n++) + { values[n] = items[n].Value; + } + return values; } } @@ -96,7 +104,7 @@ public object this[object key] get { // If this key is in the dictionary, return its value. - Int32 index; + int index; if (TryGetIndexOfKey(key, out index)) { // The key was found; return its value. @@ -112,7 +120,7 @@ public object this[object key] set { // If this key is in the dictionary, change its value. - Int32 index; + int index; if (TryGetIndexOfKey(key, out index)) { // The key was found; change its value. @@ -126,23 +134,26 @@ public object this[object key] } } // - private Boolean TryGetIndexOfKey(Object key, out Int32 index) + private bool TryGetIndexOfKey(object key, out int index) { - for (index = 0; index < ItemsInUse; index++) + for (index = 0; index < Count; index++) { // If the key is found, return true (the index is also returned). - if (items[index].Key.Equals(key)) return true; + if (items[index].Key.Equals(key)) + { + return true; + } } // Key not found, return false (index should be ignored by the caller). return false; } -// + // private class SimpleDictionaryEnumerator : IDictionaryEnumerator { // A copy of the SimpleDictionary object's key/value pairs. DictionaryEntry[] items; - Int32 index = -1; + int index = -1; public SimpleDictionaryEnumerator(SimpleDictionary sd) { @@ -152,22 +163,19 @@ public SimpleDictionaryEnumerator(SimpleDictionary sd) } // Return the current item. - public Object Current { get { ValidateIndex(); return items[index]; } } + public object Current { get { ValidateIndex(); return items[index]; } } // Return the current dictionary entry. - public DictionaryEntry Entry - { - get { return (DictionaryEntry) Current; } - } + public DictionaryEntry Entry => (DictionaryEntry)Current; // Return the key of the current item. - public Object Key { get { ValidateIndex(); return items[index].Key; } } + public object Key { get { ValidateIndex(); return items[index].Key; } } // Return the value of the current item. - public Object Value { get { ValidateIndex(); return items[index].Value; } } + public object Value { get { ValidateIndex(); return items[index].Value; } } // Advance to the next item. - public Boolean MoveNext() + public bool MoveNext() { if (index < items.Length - 1) { index++; return true; } return false; @@ -177,37 +185,32 @@ public Boolean MoveNext() private void ValidateIndex() { if (index < 0 || index >= items.Length) - throw new InvalidOperationException("Enumerator is before or after the collection."); + { + throw new InvalidOperationException("Enumerator is before or after the collection."); + } } // Reset the index to restart the enumeration. - public void Reset() - { - index = -1; - } + public void Reset() => index = -1; } // - public IDictionaryEnumerator GetEnumerator() - { + public IDictionaryEnumerator GetEnumerator() => // Construct and return an enumerator. - return new SimpleDictionaryEnumerator(this); - } + new SimpleDictionaryEnumerator(this); // #endregion #region ICollection Members - public bool IsSynchronized { get { return false; } } - public object SyncRoot { get { throw new NotImplementedException(); } } - public int Count { get { return ItemsInUse; } } - public void CopyTo(Array array, int index) { throw new NotImplementedException(); } + public bool IsSynchronized => false; + public object SyncRoot => throw new NotImplementedException(); + public int Count { get; private set; } = 0; + public void CopyTo(Array array, int index) => throw new NotImplementedException(); #endregion #region IEnumerable Members - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() => // Construct and return an enumerator. - return ((IDictionary)this).GetEnumerator(); - } + ((IDictionary)this).GetEnumerator(); #endregion } // @@ -215,25 +218,26 @@ IEnumerator IEnumerable.GetEnumerator() public sealed class App { - static void Main() + public static void Run() { // Create a dictionary that contains no more than three entries. - IDictionary d = new SimpleDictionary(3); - - // Add three people and their ages to the dictionary. - d.Add("Jeff", 40); - d.Add("Kristin", 34); - d.Add("Aidan", 1); + IDictionary d = new SimpleDictionary(3) + { + // Add three people and their ages to the dictionary. + { "Jeff", 40 }, + { "Kristin", 34 }, + { "Aidan", 1 } + }; - Console.WriteLine("Number of elements in dictionary = {0}", d.Count); + Console.WriteLine($"Number of elements in dictionary = {d.Count}"); - Console.WriteLine("Does dictionary contain 'Jeff'? {0}", d.Contains("Jeff")); - Console.WriteLine("Jeff's age is {0}", d["Jeff"]); + Console.WriteLine($"Does dictionary contain 'Jeff'? {d.Contains("Jeff")}"); + Console.WriteLine($"Jeff's age is {d["Jeff"]}"); // Display every entry's key and value. foreach (DictionaryEntry de in d) { - Console.WriteLine("{0} is {1} years old.", de.Key, de.Value); + Console.WriteLine($"{de.Key} is {de.Value} years old."); } // Remove an entry that exists. @@ -243,12 +247,16 @@ static void Main() d.Remove("Max"); // Show the names (keys) of the people in the dictionary. - foreach (String s in d.Keys) + foreach (string s in d.Keys) + { Console.WriteLine(s); + } // Show the ages (values) of the people in the dictionary. - foreach (Int32 age in d.Values) + foreach (int age in d.Values) + { Console.WriteLine(age); + } } } @@ -264,4 +272,4 @@ static void Main() // Aidan // 34 // 1 -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Key/Program.cs b/snippets/csharp/System.Collections/DictionaryEntry/Key/Program.cs new file mode 100644 index 00000000000..6138a945083 --- /dev/null +++ b/snippets/csharp/System.Collections/DictionaryEntry/Key/Program.cs @@ -0,0 +1,2 @@ +App.Run(); +DictionaySamples.Run(); diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Key/Project.csproj b/snippets/csharp/System.Collections/DictionaryEntry/Key/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/DictionaryEntry/Key/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Key/remarks.cs b/snippets/csharp/System.Collections/DictionaryEntry/Key/remarks.cs index 926f1429e65..42d96467fc5 100644 --- a/snippets/csharp/System.Collections/DictionaryEntry/Key/remarks.cs +++ b/snippets/csharp/System.Collections/DictionaryEntry/Key/remarks.cs @@ -1,16 +1,16 @@ using System; using System.Collections; -public class SimpleDictionary : DictionaryBase +public class SimpleDictionaryBase : DictionaryBase { } public class DictionaySamples { - public static void Main() + public static void Run() { // Create a dictionary that contains no more than three entries. - IDictionary myDictionary = new SimpleDictionary(); + IDictionary myDictionary = new SimpleDictionaryBase(); // Add three people and their ages to the dictionary. myDictionary.Add("Jeff", 40); @@ -19,7 +19,7 @@ public static void Main() // Display every entry's key and value. foreach (DictionaryEntry de in myDictionary) { - Console.WriteLine("{0} is {1} years old.", de.Key, de.Value); + Console.WriteLine($"{de.Key} is {de.Value} years old."); } // Remove an entry that exists. diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Overview/DictionaryEntrySample.cs b/snippets/csharp/System.Collections/DictionaryEntry/Overview/DictionaryEntrySample.cs index 4c85b17ff4f..912c6f61ddb 100644 --- a/snippets/csharp/System.Collections/DictionaryEntry/Overview/DictionaryEntrySample.cs +++ b/snippets/csharp/System.Collections/DictionaryEntry/Overview/DictionaryEntrySample.cs @@ -9,14 +9,15 @@ public static void Main() { // Create a new hash table. // - Hashtable openWith = new Hashtable(); - - // Add some elements to the hash table. There are no - // duplicate keys, but some of the values are duplicates. - openWith.Add("txt", "notepad.exe"); - openWith.Add("bmp", "paint.exe"); - openWith.Add("dib", "paint.exe"); - openWith.Add("rtf", "wordpad.exe"); + Hashtable openWith = new() + { + // Add some elements to the hash table. There are no + // duplicate keys, but some of the values are duplicates. + { "txt", "notepad.exe" }, + { "bmp", "paint.exe" }, + { "dib", "paint.exe" }, + { "rtf", "wordpad.exe" } + }; // When you use foreach to enumerate hash table elements, // the elements are retrieved as DictionaryEntry objects. @@ -24,7 +25,7 @@ public static void Main() // foreach (DictionaryEntry de in openWith) { - Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); + Console.WriteLine($"Key = {de.Key}, Value = {de.Value}"); } // } @@ -37,4 +38,4 @@ public static void Main() Key = dib, Value = paint.exe Key = bmp, Value = paint.exe */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/DictionaryEntry/Overview/Project.csproj b/snippets/csharp/System.Collections/DictionaryEntry/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/DictionaryEntry/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/DictionaryEntry/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/Program.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/Program.cs new file mode 100644 index 00000000000..650fafed5a6 --- /dev/null +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/Program.cs @@ -0,0 +1,5 @@ +SamplesHashtableDefault.Run(); +SamplesHashtableDictionary.Run(); +SamplesHashtableDictionaryLoadFactor.Run(); +SamplesHashtableCapacity.Run(); +SamplesHashtableCapacityLoadFactor.Run(); diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/Project.csproj b/snippets/csharp/System.Collections/Hashtable/.ctor/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctor.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctor.cs index 864325f716f..945bbdf7ef8 100644 --- a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctor.cs +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctor.cs @@ -7,82 +7,72 @@ using System.Collections; using System.Globalization; -class myComparer : IEqualityComparer +class DefaultEqualityComparer : IEqualityComparer { - public new bool Equals(object x, object y) - { - return x.Equals(y); - } + public new bool Equals(object x, object y) => x.Equals(y); - public int GetHashCode(object obj) - { - return obj.ToString().ToLower().GetHashCode(); - } + public int GetHashCode(object obj) => obj.ToString().ToLower().GetHashCode(); } // -class myCultureComparer : IEqualityComparer +class CultureEqualityComparer : IEqualityComparer { public CaseInsensitiveComparer myComparer; - public myCultureComparer() - { - myComparer = CaseInsensitiveComparer.DefaultInvariant; - } + public CultureEqualityComparer() => myComparer = CaseInsensitiveComparer.DefaultInvariant; - public myCultureComparer(CultureInfo myCulture) - { - myComparer = new CaseInsensitiveComparer(myCulture); - } + public CultureEqualityComparer(CultureInfo myCulture) => myComparer = new(myCulture); - public new bool Equals(object x, object y) - { - return myComparer.Compare(x, y) == 0; - } + public new bool Equals(object x, object y) => myComparer.Compare(x, y) == 0; - public int GetHashCode(object obj) - { - return obj.ToString().ToLower().GetHashCode(); - } + public int GetHashCode(object obj) => obj.ToString().ToLower().GetHashCode(); } // -public class SamplesHashtable +public class SamplesHashtableDefault { - public static void Main() + public static void Run() { // Create a hash table using the default comparer. - var myHT1 = new Hashtable(); - myHT1.Add("FIRST", "Hello"); - myHT1.Add("SECOND", "World"); - myHT1.Add("THIRD", "!"); + Hashtable myHT1 = new Hashtable() + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using the specified IEqualityComparer that uses // the default Object.Equals to determine equality. - var myHT2 = new Hashtable(new myComparer()); - myHT2.Add("FIRST", "Hello"); - myHT2.Add("SECOND", "World"); - myHT2.Add("THIRD", "!"); + Hashtable myHT2 = new Hashtable(new DefaultEqualityComparer()) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using a case-insensitive hash code provider and // case-insensitive comparer based on the InvariantCulture. Hashtable myHT3 = new Hashtable( CaseInsensitiveHashCodeProvider.DefaultInvariant, - CaseInsensitiveComparer.DefaultInvariant); - myHT3.Add("FIRST", "Hello"); - myHT3.Add("SECOND", "World"); - myHT3.Add("THIRD", "!"); + CaseInsensitiveComparer.DefaultInvariant) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using an IEqualityComparer that is based on // the Turkish culture (tr-TR) where "I" is not the uppercase // version of "i". - var myCul = new CultureInfo("tr-TR"); - var myHT4 = new Hashtable(new myCultureComparer(myCul)); - myHT4.Add("FIRST", "Hello"); - myHT4.Add("SECOND", "World"); - myHT4.Add("THIRD", "!"); + CultureInfo myCul = new("tr-TR"); + Hashtable myHT4 = new Hashtable(new CultureEqualityComparer(myCul)) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Search for a key in each hash table. Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionary.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionary.cs index 00fd0e576cc..c643f7faa42 100644 --- a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionary.cs +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionary.cs @@ -7,56 +7,47 @@ using System.Collections; using System.Globalization; -class myCultureComparer : IEqualityComparer +class DictionaryCultureEqualityComparer : IEqualityComparer { public CaseInsensitiveComparer myComparer; - public myCultureComparer() - { - myComparer = CaseInsensitiveComparer.DefaultInvariant; - } + public DictionaryCultureEqualityComparer() => myComparer = CaseInsensitiveComparer.DefaultInvariant; - public myCultureComparer(CultureInfo myCulture) - { - myComparer = new CaseInsensitiveComparer(myCulture); - } + public DictionaryCultureEqualityComparer(CultureInfo myCulture) => myComparer = new(myCulture); - public new bool Equals(object x, object y) - { - return myComparer.Compare(x, y) == 0; - } + public new bool Equals(object x, object y) => myComparer.Compare(x, y) == 0; - public int GetHashCode(object obj) - { + public int GetHashCode(object obj) => // Compare the hash code for the lowercase versions of the strings. - return obj.ToString().ToLower().GetHashCode(); - } + obj.ToString().ToLower().GetHashCode(); } -public class SamplesHashtable +public class SamplesHashtableDictionary { - public static void Main() + public static void Run() { // Create the dictionary. - var mySL = new SortedList(); - mySL.Add("FIRST", "Hello"); - mySL.Add("SECOND", "World"); - mySL.Add("THIRD", "!"); + SortedList mySL = new() + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using the default comparer. - var myHT1 = new Hashtable(mySL); + Hashtable myHT1 = new Hashtable(mySL); // Create a hash table using the specified IEqualityComparer that uses // the CaseInsensitiveComparer.DefaultInvariant to determine equality. - var myHT2 = new Hashtable(mySL, new myCultureComparer()); + Hashtable myHT2 = new Hashtable(mySL, new DictionaryCultureEqualityComparer()); // Create a hash table using an IEqualityComparer that is based on // the Turkish culture (tr-TR) where "I" is not the uppercase // version of "i". - var myCul = new CultureInfo("tr-TR"); - var myHT3 = new Hashtable(mySL, new myCultureComparer(myCul)); + CultureInfo myCul = new("tr-TR"); + Hashtable myHT3 = new Hashtable(mySL, new DictionaryCultureEqualityComparer(myCul)); // Search for a key in each hash table. Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionaryfloat.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionaryfloat.cs index 111e16b5fb3..4b5237408dc 100644 --- a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionaryfloat.cs +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctordictionaryfloat.cs @@ -7,19 +7,13 @@ using System.Collections; using System.Globalization; -class myCultureComparer : IEqualityComparer +class DictionaryLoadFactorCultureEqualityComparer : IEqualityComparer { public CaseInsensitiveComparer myComparer; - public myCultureComparer() - { - myComparer = CaseInsensitiveComparer.DefaultInvariant; - } + public DictionaryLoadFactorCultureEqualityComparer() => myComparer = CaseInsensitiveComparer.DefaultInvariant; - public myCultureComparer(CultureInfo myCulture) - { - myComparer = new CaseInsensitiveComparer(myCulture); - } + public DictionaryLoadFactorCultureEqualityComparer(CultureInfo myCulture) => myComparer = new(myCulture); public new bool Equals(object x, object y) { @@ -33,24 +27,24 @@ public myCultureComparer(CultureInfo myCulture) } } - public int GetHashCode(object obj) - { + public int GetHashCode(object obj) => // Compare the hash code for the lowercase versions of the strings. - return obj.ToString().ToLower().GetHashCode(); - } + obj.ToString().ToLower().GetHashCode(); } -public class SamplesHashtable +public class SamplesHashtableDictionaryLoadFactor { - public static void Main() + public static void Run() { // Create the dictionary. - SortedList mySL = new SortedList(); - mySL.Add("FIRST", "Hello"); - mySL.Add("SECOND", "World"); - mySL.Add("THIRD", "!"); + SortedList mySL = new() + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using the default comparer. Hashtable myHT1 = new Hashtable(mySL, .8f); @@ -58,18 +52,18 @@ public static void Main() // Create a hash table using the specified IEqualityComparer that uses // the CaseInsensitiveComparer.DefaultInvariant to determine equality. Hashtable myHT2 = new Hashtable(mySL, .8f, - new myCultureComparer()); + new DictionaryLoadFactorCultureEqualityComparer()); // Create a hash table using an IEqualityComparer that is based on // the Turkish culture (tr-TR) where "I" is not the uppercase // version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); - Hashtable myHT3 = new Hashtable(mySL, .8f, new myCultureComparer(myCul)); + CultureInfo myCul = new("tr-TR"); + Hashtable myHT3 = new Hashtable(mySL, .8f, new DictionaryLoadFactorCultureEqualityComparer(myCul)); // Search for a key in each hash table. - Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first")); - Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first")); - Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first")); + Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}"); } } @@ -84,4 +78,4 @@ Results vary depending on the system's culture settings. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorint.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorint.cs index cb36c92f928..dc4d5f4857a 100644 --- a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorint.cs +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorint.cs @@ -7,19 +7,13 @@ using System.Collections; using System.Globalization; -class myCultureComparer : IEqualityComparer +class CapacityCultureEqualityComparer : IEqualityComparer { public CaseInsensitiveComparer myComparer; - public myCultureComparer() - { - myComparer = CaseInsensitiveComparer.DefaultInvariant; - } + public CapacityCultureEqualityComparer() => myComparer = CaseInsensitiveComparer.DefaultInvariant; - public myCultureComparer(CultureInfo myCulture) - { - myComparer = new CaseInsensitiveComparer(myCulture); - } + public CapacityCultureEqualityComparer(CultureInfo myCulture) => myComparer = new(myCulture); public new bool Equals(object x, object y) { @@ -33,45 +27,49 @@ public myCultureComparer(CultureInfo myCulture) } } - public int GetHashCode(object obj) - { + public int GetHashCode(object obj) => // Compare the hash code for the lowercase versions of the strings. - return obj.ToString().ToLower().GetHashCode(); - } + obj.ToString().ToLower().GetHashCode(); } -public class SamplesHashtable +public class SamplesHashtableCapacity { - public static void Main() + public static void Run() { // Create a hash table using the default comparer. - Hashtable myHT1 = new Hashtable(3); - myHT1.Add("FIRST", "Hello"); - myHT1.Add("SECOND", "World"); - myHT1.Add("THIRD", "!"); + Hashtable myHT1 = new Hashtable(3) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using the specified IEqualityComparer that uses // the CaseInsensitiveComparer.DefaultInvariant to determine equality. - Hashtable myHT2 = new Hashtable(3, new myCultureComparer()); - myHT2.Add("FIRST", "Hello"); - myHT2.Add("SECOND", "World"); - myHT2.Add("THIRD", "!"); + Hashtable myHT2 = new Hashtable(3, new CapacityCultureEqualityComparer()) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using an IEqualityComparer that is based on // the Turkish culture (tr-TR) where "I" is not the uppercase // version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); - Hashtable myHT3 = new Hashtable(3, new myCultureComparer(myCul)); - myHT3.Add("FIRST", "Hello"); - myHT3.Add("SECOND", "World"); - myHT3.Add("THIRD", "!"); + CultureInfo myCul = new("tr-TR"); + Hashtable myHT3 = new Hashtable(3, new CapacityCultureEqualityComparer(myCul)) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Search for a key in each hash table. - Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first")); - Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first")); - Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first")); + Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}"); } } diff --git a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorintfloat.cs b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorintfloat.cs index 363f4d597be..6d6ccd39144 100644 --- a/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorintfloat.cs +++ b/snippets/csharp/System.Collections/Hashtable/.ctor/hashtable_ctorintfloat.cs @@ -7,19 +7,13 @@ using System.Collections; using System.Globalization; -class myCultureComparer : IEqualityComparer +class CapacityLoadFactorCultureEqualityComparer : IEqualityComparer { public CaseInsensitiveComparer myComparer; - public myCultureComparer() - { - myComparer = CaseInsensitiveComparer.DefaultInvariant; - } + public CapacityLoadFactorCultureEqualityComparer() => myComparer = CaseInsensitiveComparer.DefaultInvariant; - public myCultureComparer(CultureInfo myCulture) - { - myComparer = new CaseInsensitiveComparer(myCulture); - } + public CapacityLoadFactorCultureEqualityComparer(CultureInfo myCulture) => myComparer = new(myCulture); public new bool Equals(object x, object y) { @@ -33,46 +27,49 @@ public myCultureComparer(CultureInfo myCulture) } } - public int GetHashCode(object obj) - { + public int GetHashCode(object obj) => // Compare the hash code for the lowercase versions of the strings. - return obj.ToString().ToLower().GetHashCode(); - } + obj.ToString().ToLower().GetHashCode(); } -public class SamplesHashtable +public class SamplesHashtableCapacityLoadFactor { - public static void Main() + public static void Run() { // Create a hash table using the default comparer. - Hashtable myHT1 = new Hashtable(3, .8f); - myHT1.Add("FIRST", "Hello"); - myHT1.Add("SECOND", "World"); - myHT1.Add("THIRD", "!"); + Hashtable myHT1 = new Hashtable(3, .8f) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using the specified IEqualityComparer that uses // the CaseInsensitiveComparer.DefaultInvariant to determine equality. - Hashtable myHT2 = new Hashtable(3, .8f, new myCultureComparer()); - myHT2.Add("FIRST", "Hello"); - myHT2.Add("SECOND", "World"); - myHT2.Add("THIRD", "!"); + Hashtable myHT2 = new Hashtable(3, .8f, new CapacityLoadFactorCultureEqualityComparer()) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a hash table using an IEqualityComparer that is based on // the Turkish culture (tr-TR) where "I" is not the uppercase // version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); - Hashtable myHT3 = new Hashtable(3, .8f, new myCultureComparer(myCul)); - - myHT3.Add("FIRST", "Hello"); - myHT3.Add("SECOND", "World"); - myHT3.Add("THIRD", "!"); + CultureInfo myCul = new("tr-TR"); + Hashtable myHT3 = new Hashtable(3, .8f, new CapacityLoadFactorCultureEqualityComparer(myCul)) + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Search for a key in each hash table. - Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first")); - Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first")); - Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first")); + Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}"); + Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}"); } } diff --git a/snippets/csharp/System.Collections/Hashtable/Add/source.cs b/snippets/csharp/System.Collections/Hashtable/Add/source.cs index 27878b705de..5d9b66c8536 100644 --- a/snippets/csharp/System.Collections/Hashtable/Add/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/Add/source.cs @@ -1,39 +1,42 @@ // - using System; - using System.Collections; - public class SamplesHashtable - { +using System; +using System.Collections; +public class SamplesHashtable +{ public static void Main() { - // Creates and initializes a new Hashtable. - var myHT = new Hashtable(); - myHT.Add("one", "The"); - myHT.Add("two", "quick"); - myHT.Add("three", "brown"); - myHT.Add("four", "fox"); + // Creates and initializes a new Hashtable. + Hashtable myHT = new(); + myHT.Add("one", "The"); + myHT.Add("two", "quick"); + myHT.Add("three", "brown"); + myHT.Add("four", "fox"); - // Displays the Hashtable. - Console.WriteLine("The Hashtable contains the following:"); - PrintKeysAndValues(myHT); + // Displays the Hashtable. + Console.WriteLine("The Hashtable contains the following:"); + PrintKeysAndValues(myHT); } - public static void PrintKeysAndValues( Hashtable myHT ) + public static void PrintKeysAndValues(Hashtable myHT) { - Console.WriteLine("\t-KEY-\t-VALUE-"); - foreach (DictionaryEntry de in myHT) - Console.WriteLine($"\t{de.Key}:\t{de.Value}"); - Console.WriteLine(); + Console.WriteLine("\t-KEY-\t-VALUE-"); + foreach (DictionaryEntry de in myHT) + { + Console.WriteLine($"\t{de.Key}:\t{de.Value}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The Hashtable contains the following: - -KEY- -VALUE- - two: quick - three: brown - four: fox - one: The - */ +The Hashtable contains the following: + -KEY- -VALUE- + two: quick + three: brown + four: fox + one: The +*/ // diff --git a/snippets/csharp/System.Collections/Hashtable/Clear/source.cs b/snippets/csharp/System.Collections/Hashtable/Clear/source.cs index e82b179491d..e7ab8e6ae04 100644 --- a/snippets/csharp/System.Collections/Hashtable/Clear/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/Clear/source.cs @@ -1,63 +1,68 @@ // - using System; - using System.Collections; - public class SamplesHashtable - { +using System; +using System.Collections; +public class SamplesHashtable +{ public static void Main() { - // Creates and initializes a new Hashtable. - var myHT = new Hashtable(); - myHT.Add("one", "The"); - myHT.Add("two", "quick"); - myHT.Add("three", "brown"); - myHT.Add("four", "fox"); - myHT.Add("five", "jumps"); - - // Displays the count and values of the Hashtable. - Console.WriteLine("Initially,"); - Console.WriteLine($" Count : {myHT.Count}"); - Console.WriteLine(" Values:"); - PrintKeysAndValues(myHT); - - // Clears the Hashtable. - myHT.Clear(); - - // Displays the count and values of the Hashtable. - Console.WriteLine("After Clear,"); - Console.WriteLine(" Count : {myHT.Count}"); - Console.WriteLine(" Values:" ); - PrintKeysAndValues(myHT); + // Creates and initializes a new Hashtable. + Hashtable myHT = new() + { + { "one", "The" }, + { "two", "quick" }, + { "three", "brown" }, + { "four", "fox" }, + { "five", "jumps" } + }; + + // Displays the count and values of the Hashtable. + Console.WriteLine("Initially,"); + Console.WriteLine($" Count : {myHT.Count}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(myHT); + + // Clears the Hashtable. + myHT.Clear(); + + // Displays the count and values of the Hashtable. + Console.WriteLine("After Clear,"); + Console.WriteLine($" Count : {myHT.Count}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(myHT); } - public static void PrintKeysAndValues( Hashtable myHT ) + public static void PrintKeysAndValues(Hashtable myHT) { - Console.WriteLine("\t-KEY-\t-VALUE-"); - foreach (DictionaryEntry de in myHT) - Console.WriteLine("\t{de.Key}:\t{de.Value}"); - Console.WriteLine(); + Console.WriteLine("\t-KEY-\t-VALUE-"); + foreach (DictionaryEntry de in myHT) + { + Console.WriteLine($"\t{de.Key}:\t{de.Value}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initially, - Count : 5 - Values: - -KEY- -VALUE- - two: quick - three: brown - four: fox - five: jumps - one: The +Initially, + Count : 5 + Values: + -KEY- -VALUE- + two: quick + three: brown + four: fox + five: jumps + one: The - After Clear, - Count : 0 - Values: - -KEY- -VALUE- +After Clear, + Count : 0 + Values: + -KEY- -VALUE- - */ +*/ // diff --git a/snippets/csharp/System.Collections/Hashtable/Contains/source.cs b/snippets/csharp/System.Collections/Hashtable/Contains/source.cs index 52c586fdac8..79653fc1f15 100644 --- a/snippets/csharp/System.Collections/Hashtable/Contains/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/Contains/source.cs @@ -1,62 +1,67 @@ // - using System; - using System.Collections; - public class SamplesHashtable - { +using System; +using System.Collections; +public class SamplesHashtable +{ public static void Main() { - // Creates and initializes a new Hashtable. - var myHT = new Hashtable(); - myHT.Add(0, "zero"); - myHT.Add(1, "one"); - myHT.Add(2, "two"); - myHT.Add(3, "three"); - myHT.Add(4, "four"); - - // Displays the values of the Hashtable. - Console.WriteLine("The Hashtable contains the following values:"); - PrintIndexAndKeysAndValues(myHT); - - // Searches for a specific key. - int myKey = 2; - Console.WriteLine("The key \"{0}\" is {1}.", myKey, myHT.ContainsKey(myKey) ? "in the Hashtable" : "NOT in the Hashtable"); - myKey = 6; - Console.WriteLine("The key \"{0}\" is {1}.", myKey, myHT.ContainsKey(myKey) ? "in the Hashtable" : "NOT in the Hashtable"); - - // Searches for a specific value. - var myValue = "three"; - Console.WriteLine("The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable"); - myValue = "nine"; - Console.WriteLine("The value \"{0}\" is {1}.", myValue, myHT.ContainsValue( myValue ) ? "in the Hashtable" : "NOT in the Hashtable"); + // Creates and initializes a new Hashtable. + Hashtable myHT = new() + { + { 0, "zero" }, + { 1, "one" }, + { 2, "two" }, + { 3, "three" }, + { 4, "four" } + }; + + // Displays the values of the Hashtable. + Console.WriteLine("The Hashtable contains the following values:"); + PrintIndexAndKeysAndValues(myHT); + + // Searches for a specific key. + int myKey = 2; + Console.WriteLine($"""The key "{myKey}" is {(myHT.ContainsKey(myKey) ? "in the Hashtable" : "NOT in the Hashtable")}."""); + myKey = 6; + Console.WriteLine($"The key \"{myKey}\" is {(myHT.ContainsKey(myKey) ? "in the Hashtable" : "NOT in the Hashtable")}."); + + // Searches for a specific value. + string myValue = "three"; + Console.WriteLine($"The value \"{myValue}\" is {(myHT.ContainsValue(myValue) ? "in the Hashtable" : "NOT in the Hashtable")}."); + myValue = "nine"; + Console.WriteLine($"The value \"{myValue}\" is {(myHT.ContainsValue(myValue) ? "in the Hashtable" : "NOT in the Hashtable")}."); } public static void PrintIndexAndKeysAndValues(Hashtable myHT) { - int i = 0; - Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-"); - foreach (DictionaryEntry de in myHT) - Console.WriteLine($"\t[{i++}]:\t{de.Key}\t{de.Value}"); - Console.WriteLine(); + int i = 0; + Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-"); + foreach (DictionaryEntry de in myHT) + { + Console.WriteLine($"\t[{i++}]:\t{de.Key}\t{de.Value}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The Hashtable contains the following values: - -INDEX- -KEY- -VALUE- - [0]: 4 four - [1]: 3 three - [2]: 2 two - [3]: 1 one - [4]: 0 zero +The Hashtable contains the following values: + -INDEX- -KEY- -VALUE- + [0]: 4 four + [1]: 3 three + [2]: 2 two + [3]: 1 one + [4]: 0 zero - The key "2" is in the Hashtable. - The key "6" is NOT in the Hashtable. - The value "three" is in the Hashtable. - The value "nine" is NOT in the Hashtable. +The key "2" is in the Hashtable. +The key "6" is NOT in the Hashtable. +The value "three" is in the Hashtable. +The value "nine" is NOT in the Hashtable. - */ +*/ // diff --git a/snippets/csharp/System.Collections/Hashtable/CopyTo/source.cs b/snippets/csharp/System.Collections/Hashtable/CopyTo/source.cs index 3ff4d214e67..b7270147a74 100644 --- a/snippets/csharp/System.Collections/Hashtable/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/CopyTo/source.cs @@ -1,63 +1,68 @@ // - using System; - using System.Collections; - public class SamplesHashtable - { +using System; +using System.Collections; +public class SamplesHashtable +{ public static void Main() { - // Creates and initializes the source Hashtable. - var mySourceHT = new Hashtable(); - mySourceHT.Add("A", "valueA"); - mySourceHT.Add("B", "valueB"); - - // Creates and initializes the one-dimensional target Array. - var myTargetArray = new String[15]; - myTargetArray[0] = "The"; - myTargetArray[1] = "quick"; - myTargetArray[2] = "brown"; - myTargetArray[3] = "fox"; - myTargetArray[4] = "jumps"; - myTargetArray[5] = "over"; - myTargetArray[6] = "the"; - myTargetArray[7] = "lazy"; - myTargetArray[8] = "dog"; - - // Displays the values of the target Array. - Console.WriteLine("The target Array contains the following before:"); - PrintValues(myTargetArray, ' '); - - // Copies the keys in the source Hashtable to the target Hashtable, starting at index 6. - Console.WriteLine("After copying the keys, starting at index 6:"); - mySourceHT.Keys.CopyTo(myTargetArray, 6); - - // Displays the values of the target Array. - PrintValues(myTargetArray, ' '); - - // Copies the values in the source Hashtable to the target Hashtable, starting at index 6. - Console.WriteLine("After copying the values, starting at index 6:"); - mySourceHT.Values.CopyTo(myTargetArray, 6); - - // Displays the values of the target Array. - PrintValues(myTargetArray, ' '); + // Creates and initializes the source Hashtable. + Hashtable mySourceHT = new() + { + { "A", "valueA" }, + { "B", "valueB" } + }; + + // Creates and initializes the one-dimensional target Array. + string[] myTargetArray = new string[15]; + myTargetArray[0] = "The"; + myTargetArray[1] = "quick"; + myTargetArray[2] = "brown"; + myTargetArray[3] = "fox"; + myTargetArray[4] = "jumps"; + myTargetArray[5] = "over"; + myTargetArray[6] = "the"; + myTargetArray[7] = "lazy"; + myTargetArray[8] = "dog"; + + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following before:"); + PrintValues(myTargetArray, ' '); + + // Copies the keys in the source Hashtable to the target Hashtable, starting at index 6. + Console.WriteLine("After copying the keys, starting at index 6:"); + mySourceHT.Keys.CopyTo(myTargetArray, 6); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); + + // Copies the values in the source Hashtable to the target Hashtable, starting at index 6. + Console.WriteLine("After copying the values, starting at index 6:"); + mySourceHT.Values.CopyTo(myTargetArray, 6); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); } - public static void PrintValues(String[] myArr, char mySeparator) + public static void PrintValues(string[] myArr, char mySeparator) { - for (int i = 0; i < myArr.Length; i++) - Console.Write($"{mySeparator}{myArr[i]}"); - Console.WriteLine(); + for (int i = 0; i < myArr.Length; i++) + { + Console.Write($"{mySeparator}{myArr[i]}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. - - The target Array contains the following before: - The quick brown fox jumps over the lazy dog - After copying the keys, starting at index 6: - The quick brown fox jumps over B A dog - After copying the values, starting at index 6: - The quick brown fox jumps over valueB valueA dog - - */ +} +/* +This code produces the following output. + +The target Array contains the following before: + The quick brown fox jumps over the lazy dog +After copying the keys, starting at index 6: + The quick brown fox jumps over B A dog +After copying the values, starting at index 6: + The quick brown fox jumps over valueB valueA dog + +*/ // diff --git a/snippets/csharp/System.Collections/Hashtable/GetEnumerator/source2.cs b/snippets/csharp/System.Collections/Hashtable/GetEnumerator/source2.cs index 612275ae002..01ea9f15602 100644 --- a/snippets/csharp/System.Collections/Hashtable/GetEnumerator/source2.cs +++ b/snippets/csharp/System.Collections/Hashtable/GetEnumerator/source2.cs @@ -7,17 +7,19 @@ public class HashtableExample public static void Main() { // Creates and initializes a new Hashtable. - Hashtable clouds = new Hashtable(); - clouds.Add("Cirrus", "Castellanus"); - clouds.Add("Cirrocumulus", "Stratiformis"); - clouds.Add("Altostratus", "Radiatus"); - clouds.Add("Stratocumulus", "Perlucidus"); - clouds.Add("Stratus", "Fractus"); - clouds.Add("Nimbostratus", "Pannus"); - clouds.Add("Cumulus", "Humilis"); - clouds.Add("Cumulonimbus", "Incus"); + Hashtable clouds = new() + { + { "Cirrus", "Castellanus" }, + { "Cirrocumulus", "Stratiformis" }, + { "Altostratus", "Radiatus" }, + { "Stratocumulus", "Perlucidus" }, + { "Stratus", "Fractus" }, + { "Nimbostratus", "Pannus" }, + { "Cumulus", "Humilis" }, + { "Cumulonimbus", "Incus" } + }; - // Displays the keys and values of the Hashtable using GetEnumerator() + // Displays the keys and values of the Hashtable using GetEnumerator(). IDictionaryEnumerator denum = clouds.GetEnumerator(); DictionaryEntry dentry; @@ -27,18 +29,18 @@ public static void Main() Console.WriteLine(" -----------------------------"); while (denum.MoveNext()) { - dentry = (DictionaryEntry) denum.Current; - Console.WriteLine(" {0,-17}{1}", dentry.Key, dentry.Value); + dentry = (DictionaryEntry)denum.Current; + Console.WriteLine($" {dentry.Key,-17}{dentry.Value}"); } Console.WriteLine(); - // Displays the keys and values of the Hashtable using foreach statement + // Displays the keys and values of the Hashtable using foreach statement. Console.WriteLine(" Cloud Type Variation"); Console.WriteLine(" -----------------------------"); foreach (DictionaryEntry de in clouds) { - Console.WriteLine(" {0,-17}{1}", de.Key, de.Value); + Console.WriteLine($" {de.Key,-17}{de.Value}"); } Console.WriteLine(); } @@ -67,4 +69,4 @@ public static void Main() // Stratus Fractus // Altostratus Radiatus // Cumulonimbus Incus*/ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Program.cs b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Program.cs new file mode 100644 index 00000000000..07cc764299b --- /dev/null +++ b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Program.cs @@ -0,0 +1,2 @@ +SamplesHashtable.Run(); +SamplesHashtable2.Run(); diff --git a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Project.csproj index 1fe9fd2be20..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesHashtable \ No newline at end of file diff --git a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/remarks.cs b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/remarks.cs index bacf291c146..ae777ab90a4 100644 --- a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/remarks.cs +++ b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/remarks.cs @@ -3,10 +3,10 @@ public class SamplesHashtable { - public static void Main() + public static void Run() { // - var myCollection = new Hashtable(); + Hashtable myCollection = []; lock (myCollection.SyncRoot) { foreach (object item in myCollection) diff --git a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/source.cs b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/source.cs index 06948b3d013..e7faf1583a6 100644 --- a/snippets/csharp/System.Collections/Hashtable/IsSynchronized/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/IsSynchronized/source.cs @@ -4,22 +4,24 @@ public class SamplesHashtable2 { - public static void Main() + public static void Run() { // Creates and initializes a new Hashtable. - var myHT = new Hashtable(); - myHT.Add(0, "zero"); - myHT.Add(1, "one"); - myHT.Add(2, "two"); - myHT.Add(3, "three"); - myHT.Add(4, "four"); + Hashtable myHT = new() + { + { 0, "zero" }, + { 1, "one" }, + { 2, "two" }, + { 3, "three" }, + { 4, "four" } + }; // Creates a synchronized wrapper around the Hashtable. Hashtable mySyncdHT = Hashtable.Synchronized(myHT); // Displays the sychronization status of both Hashtables. - Console.WriteLine("myHT is {0}.", myHT.IsSynchronized ? "synchronized" : "not synchronized"); - Console.WriteLine("mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized"); + Console.WriteLine($"myHT is {(myHT.IsSynchronized ? "synchronized" : "not synchronized")}."); + Console.WriteLine($"mySyncdHT is {(mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized")}."); } } diff --git a/snippets/csharp/System.Collections/Hashtable/Overview/Program.cs b/snippets/csharp/System.Collections/Hashtable/Overview/Program.cs new file mode 100644 index 00000000000..8da89d358e5 --- /dev/null +++ b/snippets/csharp/System.Collections/Hashtable/Overview/Program.cs @@ -0,0 +1,2 @@ +Example.Run(); +Remarks.Run(); diff --git a/snippets/csharp/System.Collections/Hashtable/Overview/Project.csproj b/snippets/csharp/System.Collections/Hashtable/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/Hashtable/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/Hashtable/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/Hashtable/Overview/hashtable_example.cs b/snippets/csharp/System.Collections/Hashtable/Overview/hashtable_example.cs index c6ad7aaf143..d067e825f37 100644 --- a/snippets/csharp/System.Collections/Hashtable/Overview/hashtable_example.cs +++ b/snippets/csharp/System.Collections/Hashtable/Overview/hashtable_example.cs @@ -4,18 +4,19 @@ class Example { - public static void Main() + public static void Run() { // Create a new hash table. // - Hashtable openWith = new Hashtable(); - - // Add some elements to the hash table. There are no - // duplicate keys, but some of the values are duplicates. - openWith.Add("txt", "notepad.exe"); - openWith.Add("bmp", "paint.exe"); - openWith.Add("dib", "paint.exe"); - openWith.Add("rtf", "wordpad.exe"); + Hashtable openWith = new() + { + // Add some elements to the hash table. There are no + // duplicate keys, but some of the values are duplicates. + { "txt", "notepad.exe" }, + { "bmp", "paint.exe" }, + { "dib", "paint.exe" }, + { "rtf", "wordpad.exe" } + }; // The Add method throws an exception if the new key is // already in the hash table. @@ -30,12 +31,12 @@ public static void Main() // The Item property is the default property, so you // can omit its name when accessing elements. - Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); + Console.WriteLine($"For key = \"rtf\", value = {openWith["rtf"]}."); // The default Item property can be used to change the value // associated with a key. openWith["rtf"] = "winword.exe"; - Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); + Console.WriteLine($"For key = \"rtf\", value = {openWith["rtf"]}."); // If a key does not exist, setting the default Item property // for that key adds a new key/value pair. @@ -46,15 +47,15 @@ public static void Main() if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); - Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); + Console.WriteLine($"Value added for key = \"ht\": {openWith["ht"]}"); } // When you use foreach to enumerate hash table elements, // the elements are retrieved as KeyValuePair objects. Console.WriteLine(); - foreach( DictionaryEntry de in openWith ) + foreach (DictionaryEntry de in openWith) { - Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); + Console.WriteLine($"Key = {de.Key}, Value = {de.Value}"); } // To get the values alone, use the Values property. @@ -63,9 +64,9 @@ public static void Main() // The elements of the ValueCollection are strongly typed // with the type that was specified for hash table values. Console.WriteLine(); - foreach( string s in valueColl ) + foreach (string s in valueColl) { - Console.WriteLine("Value = {0}", s); + Console.WriteLine($"Value = {s}"); } // To get the keys alone, use the Keys property. @@ -74,9 +75,9 @@ public static void Main() // The elements of the KeyCollection are strongly typed // with the type that was specified for hash table keys. Console.WriteLine(); - foreach( string s in keyColl ) + foreach (string s in keyColl) { - Console.WriteLine("Key = {0}", s); + Console.WriteLine($"Key = {s}"); } // Use the Remove method to remove a key/value pair. @@ -121,4 +122,4 @@ public static void Main() Remove("doc") Key "doc" is not found. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/Hashtable/Overview/remarks.cs b/snippets/csharp/System.Collections/Hashtable/Overview/remarks.cs index 902b4ff1717..b8354871f79 100644 --- a/snippets/csharp/System.Collections/Hashtable/Overview/remarks.cs +++ b/snippets/csharp/System.Collections/Hashtable/Overview/remarks.cs @@ -3,23 +3,24 @@ public class Remarks { - public static void Main() + public static void Run() { // Create a new hash table. // - Hashtable myHashtable = new Hashtable(); - - // Add some elements to the hash table. There are no - // duplicate keys, but some of the values are duplicates. - myHashtable.Add("txt", "notepad.exe"); - myHashtable.Add("bmp", "paint.exe"); - myHashtable.Add("dib", "paint.exe"); - myHashtable.Add("rtf", "wordpad.exe"); + Hashtable myHashtable = new() + { + // Add some elements to the hash table. There are no + // duplicate keys, but some of the values are duplicates. + { "txt", "notepad.exe" }, + { "bmp", "paint.exe" }, + { "dib", "paint.exe" }, + { "rtf", "wordpad.exe" } + }; // When you use foreach to enumerate hash table elements, // the elements are retrieved as KeyValuePair objects. // - foreach(DictionaryEntry de in myHashtable) + foreach (DictionaryEntry de in myHashtable) { // ... } diff --git a/snippets/csharp/System.Collections/Hashtable/Remove/source.cs b/snippets/csharp/System.Collections/Hashtable/Remove/source.cs index a3e99961fbd..b4c131246a7 100644 --- a/snippets/csharp/System.Collections/Hashtable/Remove/source.cs +++ b/snippets/csharp/System.Collections/Hashtable/Remove/source.cs @@ -1,67 +1,72 @@ // - using System; - using System.Collections; - public class SamplesHashtable - { +using System; +using System.Collections; +public class SamplesHashtable +{ public static void Main() { - // Creates and initializes a new Hashtable. - var myHT = new Hashtable(); - myHT.Add("1a", "The"); - myHT.Add("1b", "quick"); - myHT.Add("1c", "brown"); - myHT.Add("2a", "fox"); - myHT.Add("2b", "jumps"); - myHT.Add("2c", "over"); - myHT.Add("3a", "the"); - myHT.Add("3b", "lazy"); - myHT.Add("3c", "dog"); + // Creates and initializes a new Hashtable. + Hashtable myHT = new() + { + { "1a", "The" }, + { "1b", "quick" }, + { "1c", "brown" }, + { "2a", "fox" }, + { "2b", "jumps" }, + { "2c", "over" }, + { "3a", "the" }, + { "3b", "lazy" }, + { "3c", "dog" } + }; - // Displays the Hashtable. - Console.WriteLine("The Hashtable initially contains the following:"); - PrintKeysAndValues(myHT); + // Displays the Hashtable. + Console.WriteLine("The Hashtable initially contains the following:"); + PrintKeysAndValues(myHT); - // Removes the element with the key "3b". - myHT.Remove("3b"); + // Removes the element with the key "3b". + myHT.Remove("3b"); - // Displays the current state of the Hashtable. - Console.WriteLine("After removing \"lazy\":"); - PrintKeysAndValues(myHT); + // Displays the current state of the Hashtable. + Console.WriteLine("After removing \"lazy\":"); + PrintKeysAndValues(myHT); } public static void PrintKeysAndValues(Hashtable myHT) { - foreach (DictionaryEntry de in myHT) - Console.WriteLine($" {de.Key}: {de.Value}"); - Console.WriteLine(); + foreach (DictionaryEntry de in myHT) + { + Console.WriteLine($" {de.Key}: {de.Value}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The Hashtable initially contains the following: - 2c: over - 3a: the - 2b: jumps - 3b: lazy - 1b: quick - 3c: dog - 2a: fox - 1c: brown - 1a: The +The Hashtable initially contains the following: + 2c: over + 3a: the + 2b: jumps + 3b: lazy + 1b: quick + 3c: dog + 2a: fox + 1c: brown + 1a: The - After removing "lazy": - 2c: over - 3a: the - 2b: jumps - 1b: quick - 3c: dog - 2a: fox - 1c: brown - 1a: The +After removing "lazy": + 2c: over + 3a: the + 2b: jumps + 1b: quick + 3c: dog + 2a: fox + 1c: brown + 1a: The - */ +*/ // diff --git a/snippets/csharp/System.Collections/ICollection/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/ICollection/IsSynchronized/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/ICollection/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/ICollection/IsSynchronized/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/ICollection/IsSynchronized/remarks.cs b/snippets/csharp/System.Collections/ICollection/IsSynchronized/remarks.cs index 099e5d2b2f3..fc9c828a6e2 100644 --- a/snippets/csharp/System.Collections/ICollection/IsSynchronized/remarks.cs +++ b/snippets/csharp/System.Collections/ICollection/IsSynchronized/remarks.cs @@ -5,10 +5,10 @@ public class Remarks { public static void Main() { - ArrayList someCollection = new ArrayList(5); + ArrayList someCollection = new(5); // ICollection myCollection = someCollection; - lock(myCollection.SyncRoot) + lock (myCollection.SyncRoot) { foreach (object item in myCollection) { @@ -20,10 +20,10 @@ public static void Main() public static void Dummy() { - ArrayList someCollection = new ArrayList(5); + ArrayList someCollection = new(5); // ICollection myCollection = someCollection; - lock(myCollection.SyncRoot) + lock (myCollection.SyncRoot) { // Some operation on the collection, which is now thread safe. } diff --git a/snippets/csharp/System.Collections/IComparer/reverse.cs b/snippets/csharp/System.Collections/IComparer/reverse.cs index 7910d8a51e4..bb531858d33 100644 --- a/snippets/csharp/System.Collections/IComparer/reverse.cs +++ b/snippets/csharp/System.Collections/IComparer/reverse.cs @@ -3,44 +3,43 @@ public class Example { - public class ReverserClass : IComparer - { - // Call CaseInsensitiveComparer.Compare with the parameters reversed. - int IComparer.Compare(Object x, Object y) - { - return ((new CaseInsensitiveComparer()).Compare(y, x)); - } - } + public class ReverserClass : IComparer + { + // Call CaseInsensitiveComparer.Compare with the parameters reversed. + int IComparer.Compare(object x, object y) => ((new CaseInsensitiveComparer()).Compare(y, x)); + } - public static void Main() - { - // Initialize a string array. - string[] words = { "The", "quick", "brown", "fox", "jumps", "over", - "the", "lazy", "dog" }; + public static void Main() + { + // Initialize a string array. + string[] words = [ "The", "quick", "brown", "fox", "jumps", "over", + "the", "lazy", "dog" ]; - // Display the array values. - Console.WriteLine("The array initially contains the following values:" ); - PrintIndexAndValues(words); + // Display the array values. + Console.WriteLine("The array initially contains the following values:"); + PrintIndexAndValues(words); - // Sort the array values using the default comparer. - Array.Sort(words); - Console.WriteLine("After sorting with the default comparer:" ); - PrintIndexAndValues(words); + // Sort the array values using the default comparer. + Array.Sort(words); + Console.WriteLine("After sorting with the default comparer:"); + PrintIndexAndValues(words); - // Sort the array values using the reverse case-insensitive comparer. - Array.Sort(words, new ReverserClass()); - Console.WriteLine("After sorting with the reverse case-insensitive comparer:"); - PrintIndexAndValues(words); - } + // Sort the array values using the reverse case-insensitive comparer. + Array.Sort(words, new ReverserClass()); + Console.WriteLine("After sorting with the reverse case-insensitive comparer:"); + PrintIndexAndValues(words); + } - public static void PrintIndexAndValues(IEnumerable list) - { - int i = 0; - foreach (var item in list ) - Console.WriteLine($" [{i++}]: {item}"); + public static void PrintIndexAndValues(IEnumerable list) + { + int i = 0; + foreach (object item in list) + { + Console.WriteLine($" [{i++}]: {item}"); + } - Console.WriteLine(); - } + Console.WriteLine(); + } } // The example displays the following output: // The array initially contains the following values: @@ -74,4 +73,4 @@ public static void PrintIndexAndValues(IEnumerable list) // [5]: jumps // [6]: fox // [7]: dog -// [8]: brown \ No newline at end of file +// [8]: brown diff --git a/snippets/csharp/System.Collections/IEnumerable/Overview/Project.csproj b/snippets/csharp/System.Collections/IEnumerable/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/IEnumerable/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/IEnumerable/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/IEnumerable/Overview/ienumerator.cs b/snippets/csharp/System.Collections/IEnumerable/Overview/ienumerator.cs index 8d55ede3424..181c741e57e 100644 --- a/snippets/csharp/System.Collections/IEnumerable/Overview/ienumerator.cs +++ b/snippets/csharp/System.Collections/IEnumerable/Overview/ienumerator.cs @@ -2,6 +2,19 @@ using System; using System.Collections; +Person[] peopleArray = +[ + new("John", "Smith"), + new("Jim", "Johnson"), + new("Sue", "Rabon"), +]; + +People peopleList = new(peopleArray); +foreach (Person p in peopleList) +{ + Console.WriteLine($"{p.firstName} {p.lastName}"); +} + // Simple business object. public class Person { @@ -31,16 +44,10 @@ public People(Person[] pArray) } } -// Implementation for the GetEnumerator method. - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator) GetEnumerator(); - } + // Implementation for the GetEnumerator method. + IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)GetEnumerator(); - public PeopleEnum GetEnumerator() - { - return new PeopleEnum(_people); - } + public PeopleEnum GetEnumerator() => new PeopleEnum(_people); } // @@ -53,10 +60,7 @@ public class PeopleEnum : IEnumerator // until the first MoveNext() call. int position = -1; - public PeopleEnum(Person[] list) - { - _people = list; - } + public PeopleEnum(Person[] list) => _people = list; public bool MoveNext() { @@ -64,18 +68,9 @@ public bool MoveNext() return (position < _people.Length); } - public void Reset() - { - position = -1; - } + public void Reset() => position = -1; - object IEnumerator.Current - { - get - { - return Current; - } - } + object IEnumerator.Current => Current; public Person Current { @@ -94,23 +89,6 @@ public Person Current } // -class App -{ - static void Main() - { - Person[] peopleArray = new Person[3] - { - new Person("John", "Smith"), - new Person("Jim", "Johnson"), - new Person("Sue", "Rabon"), - }; - - People peopleList = new People(peopleArray); - foreach (Person p in peopleList) - Console.WriteLine(p.firstName + " " + p.lastName); - } -} - /* This code produces output similar to the following: * * John Smith @@ -118,4 +96,4 @@ static void Main() * Sue Rabon * */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/IList/Overview/Program.cs b/snippets/csharp/System.Collections/IList/Overview/Program.cs index 6bd57ce3bf2..a02903e5ddc 100644 --- a/snippets/csharp/System.Collections/IList/Overview/Program.cs +++ b/snippets/csharp/System.Collections/IList/Overview/Program.cs @@ -2,80 +2,67 @@ using System; using System.Collections; -class Program -{ - static void Main() - { - var test = new SimpleList(); - - // Populate the List. - Console.WriteLine("Populate the List"); - test.Add("one"); - test.Add("two"); - test.Add("three"); - test.Add("four"); - test.Add("five"); - test.Add("six"); - test.Add("seven"); - test.Add("eight"); - test.PrintContents(); - Console.WriteLine(); - - // Remove elements from the list. - Console.WriteLine("Remove elements from the list"); - test.Remove("six"); - test.Remove("eight"); - test.PrintContents(); - Console.WriteLine(); - - // Add an element to the end of the list. - Console.WriteLine("Add an element to the end of the list"); - test.Add("nine"); - test.PrintContents(); - Console.WriteLine(); - - // Insert an element into the middle of the list. - Console.WriteLine("Insert an element into the middle of the list"); - test.Insert(4, "number"); - test.PrintContents(); - Console.WriteLine(); - - // Check for specific elements in the list. - Console.WriteLine("Check for specific elements in the list"); - Console.WriteLine($"List contains \"three\": {test.Contains("three")}"); - Console.WriteLine($"List contains \"ten\": {test.Contains("ten")}"); - } -} +SimpleList test = []; + +// Populate the List. +Console.WriteLine("Populate the List"); +test.Add("one"); +test.Add("two"); +test.Add("three"); +test.Add("four"); +test.Add("five"); +test.Add("six"); +test.Add("seven"); +test.Add("eight"); +test.PrintContents(); +Console.WriteLine(); + +// Remove elements from the list. +Console.WriteLine("Remove elements from the list"); +test.Remove("six"); +test.Remove("eight"); +test.PrintContents(); +Console.WriteLine(); + +// Add an element to the end of the list. +Console.WriteLine("Add an element to the end of the list"); +test.Add("nine"); +test.PrintContents(); +Console.WriteLine(); + +// Insert an element into the middle of the list. +Console.WriteLine("Insert an element into the middle of the list"); +test.Insert(4, "number"); +test.PrintContents(); +Console.WriteLine(); + +// Check for specific elements in the list. +Console.WriteLine("Check for specific elements in the list"); +Console.WriteLine($"List contains \"three\": {test.Contains("three")}"); +Console.WriteLine($"List contains \"ten\": {test.Contains("ten")}"); // class SimpleList : IList { private object[] _contents = new object[8]; - private int _count; - public SimpleList() - { - _count = 0; - } + public SimpleList() => Count = 0; - // IList Members + // IList Members. public int Add(object value) { - if (_count < _contents.Length) + if (Count < _contents.Length) { - _contents[_count] = value; - _count++; + _contents[Count] = value; + Count++; - return (_count - 1); + return (Count - 1); } return -1; } - public void Clear() - { - _count = 0; - } + public void Clear() => Count = 0; public bool Contains(object value) { @@ -103,9 +90,9 @@ public int IndexOf(object value) public void Insert(int index, object value) { - if ((_count + 1 <= _contents.Length) && (index <= Count) && (index >= 0)) + if ((Count + 1 <= _contents.Length) && (index <= Count) && (index >= 0)) { - _count++; + Count++; for (int i = Count - 1; i > index; i--) { @@ -115,26 +102,11 @@ public void Insert(int index, object value) } } - public bool IsFixedSize - { - get - { - return true; - } - } + public bool IsFixedSize => true; - public bool IsReadOnly - { - get - { - return false; - } - } + public bool IsReadOnly => false; - public void Remove(object value) - { - RemoveAt(IndexOf(value)); - } + public void Remove(object value) => RemoveAt(IndexOf(value)); public void RemoveAt(int index) { @@ -144,20 +116,13 @@ public void RemoveAt(int index) { _contents[i] = _contents[i + 1]; } - _count--; + Count--; } } public object this[int index] { - get - { - return _contents[index]; - } - set - { - _contents[index] = value; - } + get => _contents[index]; set => _contents[index] = value; } // ICollection members. @@ -170,44 +135,24 @@ public void CopyTo(Array array, int index) } } - public int Count - { - get - { - return _count; - } - } + public int Count { get; private set; } - public bool IsSynchronized - { - get - { - return false; - } - } + public bool IsSynchronized => false; // Return the current instance since the underlying store is not // publicly available. - public object SyncRoot - { - get - { - return this; - } - } + public object SyncRoot => this; - // IEnumerable Members + // IEnumerable Members. - public IEnumerator GetEnumerator() - { + public IEnumerator GetEnumerator() => // Refer to the IEnumerator documentation for an example of // implementing an enumerator. throw new NotImplementedException("The method or operation is not implemented."); - } public void PrintContents() { - Console.WriteLine($"List has a capacity of {_contents.Length} and currently has {_count} elements."); + Console.WriteLine($"List has a capacity of {_contents.Length} and currently has {Count} elements."); Console.Write("List contents:"); for (int i = 0; i < Count; i++) { @@ -238,4 +183,4 @@ public void PrintContents() // Check for specific elements in the list: // List contains "three": True // List contains "ten": False -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/IList/Overview/Project.csproj b/snippets/csharp/System.Collections/IList/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/IList/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/IList/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/IStructuralEquatable/Overview/Project.csproj b/snippets/csharp/System.Collections/IStructuralEquatable/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/IStructuralEquatable/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/IStructuralEquatable/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Collections/IStructuralEquatable/Overview/nanexample1.cs b/snippets/csharp/System.Collections/IStructuralEquatable/Overview/nanexample1.cs index 26fb4873f14..afb62ecbae7 100644 --- a/snippets/csharp/System.Collections/IStructuralEquatable/Overview/nanexample1.cs +++ b/snippets/csharp/System.Collections/IStructuralEquatable/Overview/nanexample1.cs @@ -5,50 +5,53 @@ public class NanComparer : IEqualityComparer { - public new bool Equals(object x, object y) - { - if (x is float) - return (float) x == (float) y; - else if (x is double) - return (double) x == (double) y; - else - return EqualityComparer.Default.Equals(x, y); - } + public new bool Equals(object x, object y) + { + if (x is float) + { + return (float)x == (float)y; + } + else if (x is double) + { + return (double)x == (double)y; + } + else + { + return EqualityComparer.Default.Equals(x, y); + } + } - public int GetHashCode(object obj) - { - return EqualityComparer.Default.GetHashCode(obj); - } + public int GetHashCode(object obj) => EqualityComparer.Default.GetHashCode(obj); } // // public class Example { - public static void Main() - { - var t1 = Tuple.Create(12.3, Double.NaN, 16.4); - var t2 = Tuple.Create(12.3, Double.NaN, 16.4); + public static void Main() + { + Tuple t1 = Tuple.Create(12.3, double.NaN, 16.4); + Tuple t2 = Tuple.Create(12.3, double.NaN, 16.4); - // Call default Equals method. - Console.WriteLine(t1.Equals(t2)); + // Call default Equals method. + Console.WriteLine(t1.Equals(t2)); - IStructuralEquatable equ = t1; - // Call IStructuralEquatable.Equals using default comparer. - Console.WriteLine(equ.Equals(t2, EqualityComparer.Default)); + IStructuralEquatable equ = t1; + // Call IStructuralEquatable.Equals using default comparer. + Console.WriteLine(equ.Equals(t2, EqualityComparer.Default)); - // Call IStructuralEquatable.Equals using - // StructuralComparisons.StructuralEqualityComparer. - Console.WriteLine(equ.Equals(t2, - StructuralComparisons.StructuralEqualityComparer)); + // Call IStructuralEquatable.Equals using + // StructuralComparisons.StructuralEqualityComparer. + Console.WriteLine(equ.Equals(t2, + StructuralComparisons.StructuralEqualityComparer)); - // Call IStructuralEquatable.Equals using custom comparer. - Console.WriteLine(equ.Equals(t2, new NanComparer())); - } + // Call IStructuralEquatable.Equals using custom comparer. + Console.WriteLine(equ.Equals(t2, new NanComparer())); + } } // The example displays the following output: // True // True // True // False -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Collections/Queue/Clear/source.cs b/snippets/csharp/System.Collections/Queue/Clear/source.cs index 099c261540d..db19faee691 100644 --- a/snippets/csharp/System.Collections/Queue/Clear/source.cs +++ b/snippets/csharp/System.Collections/Queue/Clear/source.cs @@ -1,50 +1,54 @@ // - using System; - using System.Collections; - public class SamplesQueue { - - public static void Main() { - - // Creates and initializes a new Queue. - Queue myQ = new Queue(); - myQ.Enqueue( "The" ); - myQ.Enqueue( "quick" ); - myQ.Enqueue( "brown" ); - myQ.Enqueue( "fox" ); - myQ.Enqueue( "jumps" ); - - // Displays the count and values of the Queue. - Console.WriteLine( "Initially," ); - Console.WriteLine( " Count : {0}", myQ.Count ); - Console.Write( " Values:" ); - PrintValues( myQ ); - - // Clears the Queue. - myQ.Clear(); - - // Displays the count and values of the Queue. - Console.WriteLine( "After Clear," ); - Console.WriteLine( " Count : {0}", myQ.Count ); - Console.Write( " Values:" ); - PrintValues( myQ ); +using System; +using System.Collections; +public class SamplesQueue +{ + + public static void Main() + { + + // Creates and initializes a new Queue. + Queue myQ = new(); + myQ.Enqueue("The"); + myQ.Enqueue("quick"); + myQ.Enqueue("brown"); + myQ.Enqueue("fox"); + myQ.Enqueue("jumps"); + + // Displays the count and values of the Queue. + Console.WriteLine("Initially,"); + Console.WriteLine($" Count : {myQ.Count}"); + Console.Write(" Values:"); + PrintValues(myQ); + + // Clears the Queue. + myQ.Clear(); + + // Displays the count and values of the Queue. + Console.WriteLine("After Clear,"); + Console.WriteLine($" Count : {myQ.Count}"); + Console.Write(" Values:"); + PrintValues(myQ); } - public static void PrintValues( Queue myQ ) { - foreach ( Object myObj in myQ ) { - Console.Write( " {0}", myObj ); - } - Console.WriteLine(); + public static void PrintValues(Queue myQ) + { + foreach (object myObj in myQ) + { + Console.Write($" {myObj}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. - - Initially, - Count : 5 - Values: The quick brown fox jumps - After Clear, - Count : 0 - Values: - - */ +} +/* +This code produces the following output. + +Initially, + Count : 5 + Values: The quick brown fox jumps +After Clear, + Count : 0 + Values: + +*/ // diff --git a/snippets/csharp/System.Collections/Queue/CopyTo/source.cs b/snippets/csharp/System.Collections/Queue/CopyTo/source.cs index 5dd15610861..0de7d567ef2 100644 --- a/snippets/csharp/System.Collections/Queue/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/Queue/CopyTo/source.cs @@ -1,64 +1,68 @@ -// - using System; - using System.Collections; - public class SamplesQueue { +// +using System; +using System.Collections; +public class SamplesQueue +{ - public static void Main() { + public static void Main() + { - // Creates and initializes the source Queue. - Queue mySourceQ = new Queue(); - mySourceQ.Enqueue( "three" ); - mySourceQ.Enqueue( "napping" ); - mySourceQ.Enqueue( "cats" ); - mySourceQ.Enqueue( "in" ); - mySourceQ.Enqueue( "the" ); - mySourceQ.Enqueue( "barn" ); + // Creates and initializes the source Queue. + Queue mySourceQ = new(); + mySourceQ.Enqueue("three"); + mySourceQ.Enqueue("napping"); + mySourceQ.Enqueue("cats"); + mySourceQ.Enqueue("in"); + mySourceQ.Enqueue("the"); + mySourceQ.Enqueue("barn"); - // Creates and initializes the one-dimensional target Array. - Array myTargetArray=Array.CreateInstance( typeof(string), 15 ); - myTargetArray.SetValue( "The", 0 ); - myTargetArray.SetValue( "quick", 1 ); - myTargetArray.SetValue( "brown", 2 ); - myTargetArray.SetValue( "fox", 3 ); - myTargetArray.SetValue( "jumps", 4 ); - myTargetArray.SetValue( "over", 5 ); - myTargetArray.SetValue( "the", 6 ); - myTargetArray.SetValue( "lazy", 7 ); - myTargetArray.SetValue( "dog", 8 ); + // Creates and initializes the one-dimensional target Array. + Array myTargetArray = Array.CreateInstance(typeof(string), 15); + myTargetArray.SetValue("The", 0); + myTargetArray.SetValue("quick", 1); + myTargetArray.SetValue("brown", 2); + myTargetArray.SetValue("fox", 3); + myTargetArray.SetValue("jumps", 4); + myTargetArray.SetValue("over", 5); + myTargetArray.SetValue("the", 6); + myTargetArray.SetValue("lazy", 7); + myTargetArray.SetValue("dog", 8); - // Displays the values of the target Array. - Console.WriteLine( "The target Array contains the following (before and after copying):" ); - PrintValues( myTargetArray, ' ' ); + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following (before and after copying):"); + PrintValues(myTargetArray, ' '); - // Copies the entire source Queue to the target Array, starting at index 6. - mySourceQ.CopyTo( myTargetArray, 6 ); + // Copies the entire source Queue to the target Array, starting at index 6. + mySourceQ.CopyTo(myTargetArray, 6); - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); - // Copies the entire source Queue to a new standard array. - Object[] myStandardArray = mySourceQ.ToArray(); + // Copies the entire source Queue to a new standard array. + object[] myStandardArray = mySourceQ.ToArray(); - // Displays the values of the new standard array. - Console.WriteLine( "The new standard array contains the following:" ); - PrintValues( myStandardArray, ' ' ); + // Displays the values of the new standard array. + Console.WriteLine("The new standard array contains the following:"); + PrintValues(myStandardArray, ' '); } - public static void PrintValues( Array myArr, char mySeparator ) { - foreach ( Object myObj in myArr ) { - Console.Write( "{0}{1}", mySeparator, myObj ); - } - Console.WriteLine(); + public static void PrintValues(Array myArr, char mySeparator) + { + foreach (object myObj in myArr) + { + Console.Write($"{mySeparator}{myObj}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The target Array contains the following (before and after copying): - The quick brown fox jumps over the lazy dog - The quick brown fox jumps over three napping cats in the barn - The new standard array contains the following: - three napping cats in the barn +The target Array contains the following (before and after copying): + The quick brown fox jumps over the lazy dog + The quick brown fox jumps over three napping cats in the barn +The new standard array contains the following: + three napping cats in the barn - */ +*/ // diff --git a/snippets/csharp/System.Collections/Queue/Dequeue/source.cs b/snippets/csharp/System.Collections/Queue/Dequeue/source.cs index 50120e94cfb..19c1f9d6e9b 100644 --- a/snippets/csharp/System.Collections/Queue/Dequeue/source.cs +++ b/snippets/csharp/System.Collections/Queue/Dequeue/source.cs @@ -1,59 +1,65 @@ // - using System; - using System.Collections; - public class SamplesQueue { +using System; +using System.Collections; +public class SamplesQueue +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new Queue. - Queue myQ = new Queue(); - myQ.Enqueue( "The" ); - myQ.Enqueue( "quick" ); - myQ.Enqueue( "brown" ); - myQ.Enqueue( "fox" ); + // Creates and initializes a new Queue. + Queue myQ = new(); + myQ.Enqueue("The"); + myQ.Enqueue("quick"); + myQ.Enqueue("brown"); + myQ.Enqueue("fox"); - // Displays the Queue. - Console.Write( "Queue values:" ); - PrintValues( myQ ); + // Displays the Queue. + Console.Write("Queue values:"); + PrintValues(myQ); - // Removes an element from the Queue. - Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() ); + // Removes an element from the Queue. + Console.WriteLine($"(Dequeue)\t{myQ.Dequeue()}"); - // Displays the Queue. - Console.Write( "Queue values:" ); - PrintValues( myQ ); + // Displays the Queue. + Console.Write("Queue values:"); + PrintValues(myQ); - // Removes another element from the Queue. - Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() ); + // Removes another element from the Queue. + Console.WriteLine($"(Dequeue)\t{myQ.Dequeue()}"); - // Displays the Queue. - Console.Write( "Queue values:" ); - PrintValues( myQ ); + // Displays the Queue. + Console.Write("Queue values:"); + PrintValues(myQ); - // Views the first element in the Queue but does not remove it. - Console.WriteLine( "(Peek) \t{0}", myQ.Peek() ); + // Views the first element in the Queue but does not remove it. + Console.WriteLine($"(Peek) \t{myQ.Peek()}"); - // Displays the Queue. - Console.Write( "Queue values:" ); - PrintValues( myQ ); + // Displays the Queue. + Console.Write("Queue values:"); + PrintValues(myQ); } - public static void PrintValues( IEnumerable myCollection ) { - foreach ( Object obj in myCollection ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myCollection) + { + foreach (object obj in myCollection) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. - - Queue values: The quick brown fox - (Dequeue) The - Queue values: quick brown fox - (Dequeue) quick - Queue values: brown fox - (Peek) brown - Queue values: brown fox - - */ +} +/* +This code produces the following output. + +Queue values: The quick brown fox +(Dequeue) The +Queue values: quick brown fox +(Dequeue) quick +Queue values: brown fox +(Peek) brown +Queue values: brown fox + +*/ // diff --git a/snippets/csharp/System.Collections/Queue/IsSynchronized/Program.cs b/snippets/csharp/System.Collections/Queue/IsSynchronized/Program.cs new file mode 100644 index 00000000000..dd2e872f399 --- /dev/null +++ b/snippets/csharp/System.Collections/Queue/IsSynchronized/Program.cs @@ -0,0 +1,2 @@ +SamplesQueue.Run(); +SamplesQueue2.Run(); diff --git a/snippets/csharp/System.Collections/Queue/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/Queue/IsSynchronized/Project.csproj index f39171211c0..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/Queue/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/Queue/IsSynchronized/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesQueue \ No newline at end of file diff --git a/snippets/csharp/System.Collections/Queue/IsSynchronized/source.cs b/snippets/csharp/System.Collections/Queue/IsSynchronized/source.cs index 898347b1dd3..02b2b400360 100644 --- a/snippets/csharp/System.Collections/Queue/IsSynchronized/source.cs +++ b/snippets/csharp/System.Collections/Queue/IsSynchronized/source.cs @@ -4,10 +4,10 @@ public class SamplesQueue { - public static void Main() + public static void Run() { // Creates and initializes a new Queue. - Queue myQ = new Queue(); + Queue myQ = new(); myQ.Enqueue("The"); myQ.Enqueue("quick"); myQ.Enqueue("brown"); @@ -17,8 +17,8 @@ public static void Main() Queue mySyncdQ = Queue.Synchronized(myQ); // Displays the sychronization status of both Queues. - Console.WriteLine("myQ is {0}.", myQ.IsSynchronized ? "synchronized" : "not synchronized"); - Console.WriteLine("mySyncdQ is {0}.", mySyncdQ.IsSynchronized ? "synchronized" : "not synchronized"); + Console.WriteLine($"myQ is {(myQ.IsSynchronized ? "synchronized" : "not synchronized")}."); + Console.WriteLine($"mySyncdQ is {(mySyncdQ.IsSynchronized ? "synchronized" : "not synchronized")}."); } } /* diff --git a/snippets/csharp/System.Collections/Queue/IsSynchronized/source2.cs b/snippets/csharp/System.Collections/Queue/IsSynchronized/source2.cs index 3dc182d0dbe..848ac06ecff 100644 --- a/snippets/csharp/System.Collections/Queue/IsSynchronized/source2.cs +++ b/snippets/csharp/System.Collections/Queue/IsSynchronized/source2.cs @@ -3,10 +3,10 @@ public class SamplesQueue2 { - public static void Main() + public static void Run() { // - Queue myCollection = new Queue(); + Queue myCollection = new(); lock (myCollection.SyncRoot) { foreach (object item in myCollection) diff --git a/snippets/csharp/System.Collections/Queue/Overview/source.cs b/snippets/csharp/System.Collections/Queue/Overview/source.cs index b2b93114bcf..9a8696eaaf8 100644 --- a/snippets/csharp/System.Collections/Queue/Overview/source.cs +++ b/snippets/csharp/System.Collections/Queue/Overview/source.cs @@ -1,34 +1,40 @@ // - using System; - using System.Collections; - public class SamplesQueue { +using System; +using System.Collections; +public class SamplesQueue +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new Queue. - Queue myQ = new Queue(); - myQ.Enqueue("Hello"); - myQ.Enqueue("World"); - myQ.Enqueue("!"); + // Creates and initializes a new Queue. + Queue myQ = new(); + myQ.Enqueue("Hello"); + myQ.Enqueue("World"); + myQ.Enqueue("!"); - // Displays the properties and values of the Queue. - Console.WriteLine( "myQ" ); - Console.WriteLine( "\tCount: {0}", myQ.Count ); - Console.Write( "\tValues:" ); - PrintValues( myQ ); + // Displays the properties and values of the Queue. + Console.WriteLine("myQ"); + Console.WriteLine($"\tCount: {myQ.Count}"); + Console.Write("\tValues:"); + PrintValues(myQ); } - public static void PrintValues( IEnumerable myCollection ) { - foreach ( Object obj in myCollection ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myCollection) + { + foreach (object obj in myCollection) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - myQ - Count: 3 - Values: Hello World ! +myQ + Count: 3 + Values: Hello World ! */ // diff --git a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Program.cs b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Program.cs new file mode 100644 index 00000000000..a6ebd1e960f --- /dev/null +++ b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Program.cs @@ -0,0 +1,2 @@ +SamplesCollectionBase.Run(); +SamplesSynchronizedReadOnlyCollectionBase.Run(); diff --git a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Project.csproj b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/readonlycollectionbase.cs b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/readonlycollectionbase.cs index 33333ceecaa..63f04c3c0f8 100644 --- a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/readonlycollectionbase.cs +++ b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/readonlycollectionbase.cs @@ -4,84 +4,83 @@ using System; using System.Collections; -public class ROCollection : ReadOnlyCollectionBase { +public class ROCollection : ReadOnlyCollectionBase +{ - public ROCollection( IList sourceList ) { - InnerList.AddRange( sourceList ); - } + public ROCollection(IList sourceList) => InnerList.AddRange(sourceList); - public Object this[ int index ] { - get { - return( InnerList[index] ); - } - } + public object this[int index] => (InnerList[index]); - public int IndexOf( Object value ) { - return( InnerList.IndexOf( value ) ); - } + public int IndexOf(object value) => (InnerList.IndexOf(value)); - public bool Contains( Object value ) { - return( InnerList.Contains( value ) ); - } + public bool Contains(object value) => (InnerList.Contains(value)); } -public class SamplesCollectionBase { - - public static void Main() { - - // Create an ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "red" ); - myAL.Add( "blue" ); - myAL.Add( "yellow" ); - myAL.Add( "green" ); - myAL.Add( "orange" ); - myAL.Add( "purple" ); - - // Create a new ROCollection that contains the elements in myAL. - ROCollection myCol = new ROCollection( myAL ); - - // Display the contents of the collection using foreach. This is the preferred method. - Console.WriteLine( "Contents of the collection (using foreach):" ); - PrintValues1( myCol ); - - // Display the contents of the collection using the enumerator. - Console.WriteLine( "Contents of the collection (using enumerator):" ); - PrintValues2( myCol ); - - // Display the contents of the collection using the Count property and the Item property. - Console.WriteLine( "Contents of the collection (using Count and Item):" ); - PrintIndexAndValues( myCol ); - - // Search the collection with Contains and IndexOf. - Console.WriteLine( "Contains yellow: {0}", myCol.Contains( "yellow" ) ); - Console.WriteLine( "orange is at index {0}.", myCol.IndexOf( "orange" ) ); - Console.WriteLine(); - } - - // Uses the Count property and the Item property. - public static void PrintIndexAndValues( ROCollection myCol ) { - for ( int i = 0; i < myCol.Count; i++ ) - Console.WriteLine( " [{0}]: {1}", i, myCol[i] ); - Console.WriteLine(); - } - - // Uses the foreach statement which hides the complexity of the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintValues1( ROCollection myCol ) { - foreach ( Object obj in myCol ) - Console.WriteLine( " {0}", obj ); - Console.WriteLine(); - } - - // Uses the enumerator. - // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. - public static void PrintValues2( ROCollection myCol ) { - System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); - while ( myEnumerator.MoveNext() ) - Console.WriteLine( " {0}", myEnumerator.Current ); - Console.WriteLine(); - } +public class SamplesCollectionBase +{ + + public static void Run() + { + + // Create an ArrayList. + ArrayList myAL = ["red", "blue", "yellow", "green", "orange", "purple"]; + + // Create a new ROCollection that contains the elements in myAL. + ROCollection myCol = new(myAL); + + // Display the contents of the collection using foreach. This is the preferred method. + Console.WriteLine("Contents of the collection (using foreach):"); + PrintValues1(myCol); + + // Display the contents of the collection using the enumerator. + Console.WriteLine("Contents of the collection (using enumerator):"); + PrintValues2(myCol); + + // Display the contents of the collection using the Count property and the Item property. + Console.WriteLine("Contents of the collection (using Count and Item):"); + PrintIndexAndValues(myCol); + + // Search the collection with Contains and IndexOf. + Console.WriteLine($"Contains yellow: {myCol.Contains("yellow")}"); + Console.WriteLine($"orange is at index {myCol.IndexOf("orange")}."); + Console.WriteLine(); + } + + // Uses the Count property and the Item property. + public static void PrintIndexAndValues(ROCollection myCol) + { + for (int i = 0; i < myCol.Count; i++) + { + Console.WriteLine($" [{i}]: {myCol[i]}"); + } + + Console.WriteLine(); + } + + // Uses the foreach statement which hides the complexity of the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintValues1(ROCollection myCol) + { + foreach (object obj in myCol) + { + Console.WriteLine($" {obj}"); + } + + Console.WriteLine(); + } + + // Uses the enumerator. + // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. + public static void PrintValues2(ROCollection myCol) + { + System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator(); + while (myEnumerator.MoveNext()) + { + Console.WriteLine($" {myEnumerator.Current}"); + } + + Console.WriteLine(); + } } diff --git a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/source2.cs b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/source2.cs index 8db121f8933..3da79cac463 100644 --- a/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/source2.cs +++ b/snippets/csharp/System.Collections/ReadOnlyCollectionBase/Overview/source2.cs @@ -3,49 +3,33 @@ using System; using System.Collections; -public class ROCollection : ReadOnlyCollectionBase +public class SynchronizedROCollection : ReadOnlyCollectionBase { - public ROCollection( IList sourceList ) { - InnerList.AddRange( sourceList ); - } + public SynchronizedROCollection(IList sourceList) => InnerList.AddRange(sourceList); - public Object this[ int index ] { - get { - return( InnerList[index] ); - } - } + public object this[int index] => (InnerList[index]); - public int IndexOf( Object value ) { - return( InnerList.IndexOf( value ) ); - } + public int IndexOf(object value) => (InnerList.IndexOf(value)); - public bool Contains( Object value ) { - return( InnerList.Contains( value ) ); - } + public bool Contains(object value) => (InnerList.Contains(value)); } -public class SamplesCollectionBase +public class SamplesSynchronizedReadOnlyCollectionBase { - public static void Main() + public static void Run() { // Create an ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add( "red" ); - myAL.Add( "blue" ); - myAL.Add( "yellow" ); - myAL.Add( "green" ); - myAL.Add( "orange" ); - myAL.Add( "purple" ); + ArrayList myAL = ["red", "blue", "yellow", "green", "orange", "purple"]; - // Create a new ROCollection that contains the elements in myAL. - ROCollection myReadOnlyCollection = new ROCollection( myAL ); + // Create a new SynchronizedROCollection that contains the elements in myAL. + SynchronizedROCollection myReadOnlyCollection = new(myAL); // // Get the ICollection interface from the ReadOnlyCollectionBase // derived class. ICollection myCollection = myReadOnlyCollection; - lock(myCollection.SyncRoot) + lock (myCollection.SyncRoot) { foreach (object item in myCollection) { diff --git a/snippets/csharp/System.Collections/SortedList/.ctor/Program.cs b/snippets/csharp/System.Collections/SortedList/.ctor/Program.cs new file mode 100644 index 00000000000..48c8d624df0 --- /dev/null +++ b/snippets/csharp/System.Collections/SortedList/.ctor/Program.cs @@ -0,0 +1,3 @@ +SamplesSortedListDefault.Run(); +SamplesSortedListDictionary.Run(); +SamplesSortedListCapacity.Run(); diff --git a/snippets/csharp/System.Collections/SortedList/.ctor/Project.csproj b/snippets/csharp/System.Collections/SortedList/.ctor/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Collections/SortedList/.ctor/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctor.cs b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctor.cs index 538d48ab6c6..79f7c2d9bc2 100644 --- a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctor.cs +++ b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctor.cs @@ -7,10 +7,10 @@ using System.Collections; using System.Globalization; -public class SamplesSortedList +public class SamplesSortedListDefault { - public static void Main() + public static void Run() { // Create a SortedList using the default comparer. @@ -48,7 +48,7 @@ public static void Main() // Create a SortedList using the specified CaseInsensitiveComparer, // which is based on the Turkish culture (tr-TR), where "I" is not // the uppercase version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); + CultureInfo myCul = new("tr-TR"); SortedList mySL3 = new SortedList(new CaseInsensitiveComparer(myCul)); Console.WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):"); @@ -91,8 +91,7 @@ public static void PrintKeysAndValues(SortedList myList) Console.WriteLine(" -KEY- -VALUE-"); for (int i = 0; i < myList.Count; i++) { - Console.WriteLine(" {0,-6}: {1}", - myList.GetKey(i), myList.GetByIndex(i)); + Console.WriteLine($" {myList.GetKey(i),-6}: {myList.GetByIndex(i)}"); } Console.WriteLine(); } diff --git a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctordictionary.cs b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctordictionary.cs index 70bdcd6172d..2a70236c613 100644 --- a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctordictionary.cs +++ b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctordictionary.cs @@ -6,17 +6,19 @@ using System.Collections; using System.Globalization; -public class SamplesSortedList +public class SamplesSortedListDictionary { - public static void Main() + public static void Run() { // Create the dictionary. - Hashtable myHT = new Hashtable(); - myHT.Add("FIRST", "Hello"); - myHT.Add("SECOND", "World"); - myHT.Add("THIRD", "!"); + Hashtable myHT = new() + { + { "FIRST", "Hello" }, + { "SECOND", "World" }, + { "THIRD", "!" } + }; // Create a SortedList using the default comparer. SortedList mySL1 = new SortedList(myHT); @@ -47,7 +49,7 @@ public static void Main() // Create a SortedList using the specified CaseInsensitiveComparer, // which is based on the Turkish culture (tr-TR), where "I" is not // the uppercase version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); + CultureInfo myCul = new("tr-TR"); SortedList mySL3 = new SortedList(myHT, new CaseInsensitiveComparer(myCul)); Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):"); try @@ -82,8 +84,7 @@ public static void PrintKeysAndValues(SortedList myList) Console.WriteLine(" -KEY- -VALUE-"); for (int i = 0; i < myList.Count; i++) { - Console.WriteLine(" {0,-6}: {1}", - myList.GetKey(i), myList.GetByIndex(i)); + Console.WriteLine($" {myList.GetKey(i),-6}: {myList.GetByIndex(i)}"); } Console.WriteLine(); } diff --git a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctorint.cs b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctorint.cs index 5a74c3efce4..03a964adb5d 100644 --- a/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctorint.cs +++ b/snippets/csharp/System.Collections/SortedList/.ctor/sortedlist_ctorint.cs @@ -7,14 +7,14 @@ using System.Collections; using System.Globalization; -public class SamplesSortedList +public class SamplesSortedListCapacity { - public static void Main() + public static void Run() { // Create a SortedList using the default comparer. - SortedList mySL1 = new SortedList( 3 ); + SortedList mySL1 = new SortedList(3); Console.WriteLine("mySL1 (default):"); mySL1.Add("FIRST", "Hello"); mySL1.Add("SECOND", "World"); @@ -48,9 +48,8 @@ public static void Main() // Create a SortedList using the specified CaseInsensitiveComparer, // which is based on the Turkish culture (tr-TR), where "I" is not // the uppercase version of "i". - CultureInfo myCul = new CultureInfo("tr-TR"); - SortedList mySL3 = - new SortedList(new CaseInsensitiveComparer(myCul), 3); + CultureInfo myCul = new("tr-TR"); + SortedList mySL3 = new SortedList(new CaseInsensitiveComparer(myCul), 3); Console.WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):"); @@ -93,8 +92,7 @@ public static void PrintKeysAndValues(SortedList myList) Console.WriteLine(" -KEY- -VALUE-"); for (int i = 0; i < myList.Count; i++) { - Console.WriteLine(" {0,-6}: {1}", - myList.GetKey(i), myList.GetByIndex(i)); + Console.WriteLine($" {myList.GetKey(i),-6}: {myList.GetByIndex(i)}"); } Console.WriteLine(); } diff --git a/snippets/csharp/System.Collections/SortedList/Add/source.cs b/snippets/csharp/System.Collections/SortedList/Add/source.cs index f7200ce88b5..5985dc7bfd4 100644 --- a/snippets/csharp/System.Collections/SortedList/Add/source.cs +++ b/snippets/csharp/System.Collections/SortedList/Add/source.cs @@ -1,38 +1,42 @@ // - using System; - using System.Collections; - public class SamplesSortedList { +using System; +using System.Collections; +public class SamplesSortedList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( "one", "The" ); - mySL.Add( "two", "quick" ); - mySL.Add( "three", "brown" ); - mySL.Add( "four", "fox" ); + // Creates and initializes a new SortedList. + SortedList mySL = new(); + mySL.Add("one", "The"); + mySL.Add("two", "quick"); + mySL.Add("three", "brown"); + mySL.Add("four", "fox"); - // Displays the SortedList. - Console.WriteLine( "The SortedList contains the following:" ); - PrintKeysAndValues( mySL ); + // Displays the SortedList. + Console.WriteLine("The SortedList contains the following:"); + PrintKeysAndValues(mySL); } - public static void PrintKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t{myList.GetKey(i)}:\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The SortedList contains the following: - -KEY- -VALUE- - four: fox - one: The - three: brown - two: quick - */ - // +The SortedList contains the following: + -KEY- -VALUE- + four: fox + one: The + three: brown + two: quick +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/Clear/source.cs b/snippets/csharp/System.Collections/SortedList/Clear/source.cs index 46f9a1d9780..170212b561d 100644 --- a/snippets/csharp/System.Collections/SortedList/Clear/source.cs +++ b/snippets/csharp/System.Collections/SortedList/Clear/source.cs @@ -1,99 +1,105 @@ // - using System; - using System.Collections; - public class SamplesSortedList { +using System; +using System.Collections; +public class SamplesSortedList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( "one", "The" ); - mySL.Add( "two", "quick" ); - mySL.Add( "three", "brown" ); - mySL.Add( "four", "fox" ); - mySL.Add( "five", "jumps" ); + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { "one", "The" }, + { "two", "quick" }, + { "three", "brown" }, + { "four", "fox" }, + { "five", "jumps" } + }; - // Displays the count, capacity and values of the SortedList. - Console.WriteLine( "Initially," ); - Console.WriteLine( " Count : {0}", mySL.Count ); - Console.WriteLine( " Capacity : {0}", mySL.Capacity ); - Console.WriteLine( " Values:" ); - PrintKeysAndValues( mySL ); + // Displays the count, capacity and values of the SortedList. + Console.WriteLine("Initially,"); + Console.WriteLine($" Count : {mySL.Count}"); + Console.WriteLine($" Capacity : {mySL.Capacity}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(mySL); - // Trims the SortedList. - mySL.TrimToSize(); + // Trims the SortedList. + mySL.TrimToSize(); - // Displays the count, capacity and values of the SortedList. - Console.WriteLine( "After TrimToSize," ); - Console.WriteLine( " Count : {0}", mySL.Count ); - Console.WriteLine( " Capacity : {0}", mySL.Capacity ); - Console.WriteLine( " Values:" ); - PrintKeysAndValues( mySL ); + // Displays the count, capacity and values of the SortedList. + Console.WriteLine("After TrimToSize,"); + Console.WriteLine($" Count : {mySL.Count}"); + Console.WriteLine($" Capacity : {mySL.Capacity}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(mySL); - // Clears the SortedList. - mySL.Clear(); + // Clears the SortedList. + mySL.Clear(); - // Displays the count, capacity and values of the SortedList. - Console.WriteLine( "After Clear," ); - Console.WriteLine( " Count : {0}", mySL.Count ); - Console.WriteLine( " Capacity : {0}", mySL.Capacity ); - Console.WriteLine( " Values:" ); - PrintKeysAndValues( mySL ); + // Displays the count, capacity and values of the SortedList. + Console.WriteLine("After Clear,"); + Console.WriteLine($" Count : {mySL.Count}"); + Console.WriteLine($" Capacity : {mySL.Capacity}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(mySL); - // Trims the SortedList again. - mySL.TrimToSize(); + // Trims the SortedList again. + mySL.TrimToSize(); - // Displays the count, capacity and values of the SortedList. - Console.WriteLine( "After the second TrimToSize," ); - Console.WriteLine( " Count : {0}", mySL.Count ); - Console.WriteLine( " Capacity : {0}", mySL.Capacity ); - Console.WriteLine( " Values:" ); - PrintKeysAndValues( mySL ); + // Displays the count, capacity and values of the SortedList. + Console.WriteLine("After the second TrimToSize,"); + Console.WriteLine($" Count : {mySL.Count}"); + Console.WriteLine($" Capacity : {mySL.Capacity}"); + Console.WriteLine(" Values:"); + PrintKeysAndValues(mySL); } - public static void PrintKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t{myList.GetKey(i)}:\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - Initially, - Count : 5 - Capacity : 16 - Values: - -KEY- -VALUE- - five: jumps - four: fox - one: The - three: brown - two: quick +Initially, + Count : 5 + Capacity : 16 + Values: + -KEY- -VALUE- + five: jumps + four: fox + one: The + three: brown + two: quick - After TrimToSize, - Count : 5 - Capacity : 5 - Values: - -KEY- -VALUE- - five: jumps - four: fox - one: The - three: brown - two: quick +After TrimToSize, + Count : 5 + Capacity : 5 + Values: + -KEY- -VALUE- + five: jumps + four: fox + one: The + three: brown + two: quick - After Clear, - Count : 0 - Capacity : 16 - Values: - -KEY- -VALUE- +After Clear, + Count : 0 + Capacity : 16 + Values: + -KEY- -VALUE- - After the second TrimToSize, - Count : 0 - Capacity : 16 - Values: - -KEY- -VALUE- - */ - // +After the second TrimToSize, + Count : 0 + Capacity : 16 + Values: + -KEY- -VALUE- +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/Contains/source.cs b/snippets/csharp/System.Collections/SortedList/Contains/source.cs index 8e7ffb558f7..81fcea96d2a 100644 --- a/snippets/csharp/System.Collections/SortedList/Contains/source.cs +++ b/snippets/csharp/System.Collections/SortedList/Contains/source.cs @@ -1,58 +1,64 @@ -// - using System; - using System.Collections; - - public class SamplesSortedList { - - public static void Main() { - - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( 2, "two" ); - mySL.Add( 4, "four" ); - mySL.Add( 1, "one" ); - mySL.Add( 3, "three" ); - mySL.Add( 0, "zero" ); - - // Displays the values of the SortedList. - Console.WriteLine( "The SortedList contains the following values:" ); - PrintIndexAndKeysAndValues( mySL ); - - // Searches for a specific key. - int myKey = 2; - Console.WriteLine( "The key \"{0}\" is {1}.", myKey, mySL.ContainsKey( myKey ) ? "in the SortedList" : "NOT in the SortedList" ); - myKey = 6; - Console.WriteLine( "The key \"{0}\" is {1}.", myKey, mySL.ContainsKey( myKey ) ? "in the SortedList" : "NOT in the SortedList" ); - - // Searches for a specific value. - string myValue = "three"; - Console.WriteLine( "The value \"{0}\" is {1}.", myValue, mySL.ContainsValue( myValue ) ? "in the SortedList" : "NOT in the SortedList" ); - myValue = "nine"; - Console.WriteLine( "The value \"{0}\" is {1}.", myValue, mySL.ContainsValue( myValue ) ? "in the SortedList" : "NOT in the SortedList" ); +// +using System; +using System.Collections; + +public class SamplesSortedList +{ + + public static void Main() + { + + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { 2, "two" }, + { 4, "four" }, + { 1, "one" }, + { 3, "three" }, + { 0, "zero" } + }; + + // Displays the values of the SortedList. + Console.WriteLine("The SortedList contains the following values:"); + PrintIndexAndKeysAndValues(mySL); + + // Searches for a specific key. + int myKey = 2; + Console.WriteLine($"The key \"{myKey}\" is {(mySL.ContainsKey(myKey) ? "in the SortedList" : "NOT in the SortedList")}."); + myKey = 6; + Console.WriteLine($"The key \"{myKey}\" is {(mySL.ContainsKey(myKey) ? "in the SortedList" : "NOT in the SortedList")}."); + + // Searches for a specific value. + string myValue = "three"; + Console.WriteLine($"The value \"{myValue}\" is {(mySL.ContainsValue(myValue) ? "in the SortedList" : "NOT in the SortedList")}."); + myValue = "nine"; + Console.WriteLine($"The value \"{myValue}\" is {(mySL.ContainsValue(myValue) ? "in the SortedList" : "NOT in the SortedList")}."); } - public static void PrintIndexAndKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i, myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintIndexAndKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t[{i}]:\t{myList.GetKey(i)}\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. - - The SortedList contains the following values: - -INDEX- -KEY- -VALUE- - [0]: 0 zero - [1]: 1 one - [2]: 2 two - [3]: 3 three - [4]: 4 four - - The key "2" is in the SortedList. - The key "6" is NOT in the SortedList. - The value "three" is in the SortedList. - The value "nine" is NOT in the SortedList. - */ - // +} +/* +This code produces the following output. + +The SortedList contains the following values: + -INDEX- -KEY- -VALUE- + [0]: 0 zero + [1]: 1 one + [2]: 2 two + [3]: 3 three + [4]: 4 four + +The key "2" is in the SortedList. +The key "6" is NOT in the SortedList. +The value "three" is in the SortedList. +The value "nine" is NOT in the SortedList. +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/CopyTo/source.cs b/snippets/csharp/System.Collections/SortedList/CopyTo/source.cs index a09fdd678fc..488799fc668 100644 --- a/snippets/csharp/System.Collections/SortedList/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/SortedList/CopyTo/source.cs @@ -1,46 +1,55 @@ -// - using System; - using System.Collections; - public class SamplesSortedList { - - public static void Main() { - - // Creates and initializes the source SortedList. - SortedList mySourceList = new SortedList(); - mySourceList.Add( 2, "cats" ); - mySourceList.Add( 3, "in" ); - mySourceList.Add( 1, "napping" ); - mySourceList.Add( 4, "the" ); - mySourceList.Add( 0, "three" ); - mySourceList.Add( 5, "barn" ); - - // Creates and initializes the one-dimensional target Array. - String[] tempArray = new String[] { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" }; - DictionaryEntry[] myTargetArray = new DictionaryEntry[15]; - int i = 0; - foreach ( string s in tempArray ) { - myTargetArray[i].Key = i; - myTargetArray[i].Value = s; - i++; - } - - // Displays the values of the target Array. - Console.WriteLine( "The target Array contains the following (before and after copying):" ); - PrintValues( myTargetArray, ' ' ); - - // Copies the entire source SortedList to the target SortedList, starting at index 6. - mySourceList.CopyTo( myTargetArray, 6 ); - - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); +// +using System; +using System.Collections; +public class SamplesSortedList +{ + + public static void Main() + { + + // Creates and initializes the source SortedList. + SortedList mySourceList = new() + { + { 2, "cats" }, + { 3, "in" }, + { 1, "napping" }, + { 4, "the" }, + { 0, "three" }, + { 5, "barn" } + }; + + // Creates and initializes the one-dimensional target Array. + string[] tempArray = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]; + DictionaryEntry[] myTargetArray = new DictionaryEntry[15]; + int i = 0; + foreach (string s in tempArray) + { + myTargetArray[i].Key = i; + myTargetArray[i].Value = s; + i++; + } + + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following (before and after copying):"); + PrintValues(myTargetArray, ' '); + + // Copies the entire source SortedList to the target SortedList, starting at index 6. + mySourceList.CopyTo(myTargetArray, 6); + + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); } - public static void PrintValues( DictionaryEntry[] myArr, char mySeparator ) { - for ( int i = 0; i < myArr.Length; i++ ) - Console.Write( "{0}{1}", mySeparator, myArr[i].Value ); - Console.WriteLine(); + public static void PrintValues(DictionaryEntry[] myArr, char mySeparator) + { + for (int i = 0; i < myArr.Length; i++) + { + Console.Write($"{mySeparator}{myArr[i].Value}"); + } + + Console.WriteLine(); } - } +} /* diff --git a/snippets/csharp/System.Collections/SortedList/GetByIndex/source.cs b/snippets/csharp/System.Collections/SortedList/GetByIndex/source.cs index a6109eadb6d..0d67e663edf 100644 --- a/snippets/csharp/System.Collections/SortedList/GetByIndex/source.cs +++ b/snippets/csharp/System.Collections/SortedList/GetByIndex/source.cs @@ -1,51 +1,57 @@ // - using System; - using System.Collections; - public class SamplesSortedList { +using System; +using System.Collections; +public class SamplesSortedList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( 1.3, "fox" ); - mySL.Add( 1.4, "jumps" ); - mySL.Add( 1.5, "over" ); - mySL.Add( 1.2, "brown" ); - mySL.Add( 1.1, "quick" ); - mySL.Add( 1.0, "The" ); - mySL.Add( 1.6, "the" ); - mySL.Add( 1.8, "dog" ); - mySL.Add( 1.7, "lazy" ); + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { 1.3, "fox" }, + { 1.4, "jumps" }, + { 1.5, "over" }, + { 1.2, "brown" }, + { 1.1, "quick" }, + { 1.0, "The" }, + { 1.6, "the" }, + { 1.8, "dog" }, + { 1.7, "lazy" } + }; - // Gets the key and the value based on the index. - int myIndex=3; - Console.WriteLine( "The key at index {0} is {1}.", myIndex, mySL.GetKey( myIndex ) ); - Console.WriteLine( "The value at index {0} is {1}.", myIndex, mySL.GetByIndex( myIndex ) ); + // Gets the key and the value based on the index. + int myIndex = 3; + Console.WriteLine($"The key at index {myIndex} is {mySL.GetKey(myIndex)}."); + Console.WriteLine($"The value at index {myIndex} is {mySL.GetByIndex(myIndex)}."); - // Gets the list of keys and the list of values. - IList myKeyList = mySL.GetKeyList(); - IList myValueList = mySL.GetValueList(); + // Gets the list of keys and the list of values. + IList myKeyList = mySL.GetKeyList(); + IList myValueList = mySL.GetValueList(); - // Prints the keys in the first column and the values in the second column. - Console.WriteLine( "\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < mySL.Count; i++ ) - Console.WriteLine( "\t{0}\t{1}", myKeyList[i], myValueList[i] ); + // Prints the keys in the first column and the values in the second column. + Console.WriteLine("\t-KEY-\t-VALUE-"); + for (int i = 0; i < mySL.Count; i++) + { + Console.WriteLine($"\t{myKeyList[i]}\t{myValueList[i]}"); + } } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The key at index 3 is 1.3. - The value at index 3 is fox. - -KEY- -VALUE- - 1 The - 1.1 quick - 1.2 brown - 1.3 fox - 1.4 jumps - 1.5 over - 1.6 the - 1.7 lazy - 1.8 dog - */ - // +The key at index 3 is 1.3. +The value at index 3 is fox. + -KEY- -VALUE- + 1 The + 1.1 quick + 1.2 brown + 1.3 fox + 1.4 jumps + 1.5 over + 1.6 the + 1.7 lazy + 1.8 dog +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/IndexOfKey/source.cs b/snippets/csharp/System.Collections/SortedList/IndexOfKey/source.cs index a5e81966cf0..fce73a0ceef 100644 --- a/snippets/csharp/System.Collections/SortedList/IndexOfKey/source.cs +++ b/snippets/csharp/System.Collections/SortedList/IndexOfKey/source.cs @@ -1,51 +1,57 @@ -// - using System; - using System.Collections; - public class SamplesSortedList { - - public static void Main() { - - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( 1, "one" ); - mySL.Add( 3, "three" ); - mySL.Add( 2, "two" ); - mySL.Add( 4, "four" ); - mySL.Add( 0, "zero" ); - - // Displays the values of the SortedList. - Console.WriteLine( "The SortedList contains the following values:" ); - PrintIndexAndKeysAndValues( mySL ); - - // Searches for a specific key. - int myKey = 2; - Console.WriteLine( "The key \"{0}\" is at index {1}.", myKey, mySL.IndexOfKey( myKey ) ); - - // Searches for a specific value. - string myValue = "three"; - Console.WriteLine( "The value \"{0}\" is at index {1}.", myValue, mySL.IndexOfValue( myValue ) ); +// +using System; +using System.Collections; +public class SamplesSortedList +{ + + public static void Main() + { + + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { 1, "one" }, + { 3, "three" }, + { 2, "two" }, + { 4, "four" }, + { 0, "zero" } + }; + + // Displays the values of the SortedList. + Console.WriteLine("The SortedList contains the following values:"); + PrintIndexAndKeysAndValues(mySL); + + // Searches for a specific key. + int myKey = 2; + Console.WriteLine($"The key \"{myKey}\" is at index {mySL.IndexOfKey(myKey)}."); + + // Searches for a specific value. + string myValue = "three"; + Console.WriteLine($"The value \"{myValue}\" is at index {mySL.IndexOfValue(myValue)}."); } - public static void PrintIndexAndKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i, myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintIndexAndKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t[{i}]:\t{myList.GetKey(i)}\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. - - The SortedList contains the following values: - -INDEX- -KEY- -VALUE- - [0]: 0 zero - [1]: 1 one - [2]: 2 two - [3]: 3 three - [4]: 4 four - - The key "2" is at index 2. - The value "three" is at index 3. - */ - // +} +/* +This code produces the following output. + +The SortedList contains the following values: + -INDEX- -KEY- -VALUE- + [0]: 0 zero + [1]: 1 one + [2]: 2 two + [3]: 3 three + [4]: 4 four + +The key "2" is at index 2. +The value "three" is at index 3. +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/IsSynchronized/Program.cs b/snippets/csharp/System.Collections/SortedList/IsSynchronized/Program.cs new file mode 100644 index 00000000000..e3749f6ca9a --- /dev/null +++ b/snippets/csharp/System.Collections/SortedList/IsSynchronized/Program.cs @@ -0,0 +1,2 @@ +SamplesSortedList.Run(); +SamplesSortedList2.Run(); diff --git a/snippets/csharp/System.Collections/SortedList/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/SortedList/IsSynchronized/Project.csproj index 962d7dcf06e..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/SortedList/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/SortedList/IsSynchronized/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesSortedList \ No newline at end of file diff --git a/snippets/csharp/System.Collections/SortedList/IsSynchronized/source.cs b/snippets/csharp/System.Collections/SortedList/IsSynchronized/source.cs index 2b4f2b89705..7c5c7abbc6e 100644 --- a/snippets/csharp/System.Collections/SortedList/IsSynchronized/source.cs +++ b/snippets/csharp/System.Collections/SortedList/IsSynchronized/source.cs @@ -4,22 +4,24 @@ public class SamplesSortedList { - public static void Main() + public static void Run() { // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add(2, "two"); - mySL.Add(3, "three"); - mySL.Add(1, "one"); - mySL.Add(0, "zero"); - mySL.Add(4, "four"); + SortedList mySL = new() + { + { 2, "two" }, + { 3, "three" }, + { 1, "one" }, + { 0, "zero" }, + { 4, "four" } + }; // Creates a synchronized wrapper around the SortedList. SortedList mySyncdSL = SortedList.Synchronized(mySL); // Displays the sychronization status of both SortedLists. - Console.WriteLine("mySL is {0}.", mySL.IsSynchronized ? "synchronized" : "not synchronized"); - Console.WriteLine("mySyncdSL is {0}.", mySyncdSL.IsSynchronized ? "synchronized" : "not synchronized"); + Console.WriteLine($"mySL is {(mySL.IsSynchronized ? "synchronized" : "not synchronized")}."); + Console.WriteLine($"mySyncdSL is {(mySyncdSL.IsSynchronized ? "synchronized" : "not synchronized")}."); } } /* diff --git a/snippets/csharp/System.Collections/SortedList/IsSynchronized/source2.cs b/snippets/csharp/System.Collections/SortedList/IsSynchronized/source2.cs index 493b6281e65..ab3d963b696 100644 --- a/snippets/csharp/System.Collections/SortedList/IsSynchronized/source2.cs +++ b/snippets/csharp/System.Collections/SortedList/IsSynchronized/source2.cs @@ -3,10 +3,10 @@ public class SamplesSortedList2 { - public static void Main() + public static void Run() { // - SortedList myCollection = new SortedList(); + SortedList myCollection = []; lock (myCollection.SyncRoot) { foreach (object item in myCollection) diff --git a/snippets/csharp/System.Collections/SortedList/Overview/Program.cs b/snippets/csharp/System.Collections/SortedList/Overview/Program.cs new file mode 100644 index 00000000000..e3749f6ca9a --- /dev/null +++ b/snippets/csharp/System.Collections/SortedList/Overview/Program.cs @@ -0,0 +1,2 @@ +SamplesSortedList.Run(); +SamplesSortedList2.Run(); diff --git a/snippets/csharp/System.Collections/SortedList/Overview/Project.csproj b/snippets/csharp/System.Collections/SortedList/Overview/Project.csproj index 962d7dcf06e..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/SortedList/Overview/Project.csproj +++ b/snippets/csharp/System.Collections/SortedList/Overview/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesSortedList \ No newline at end of file diff --git a/snippets/csharp/System.Collections/SortedList/Overview/remarks.cs b/snippets/csharp/System.Collections/SortedList/Overview/remarks.cs index 57a123178e1..26847b765c2 100644 --- a/snippets/csharp/System.Collections/SortedList/Overview/remarks.cs +++ b/snippets/csharp/System.Collections/SortedList/Overview/remarks.cs @@ -3,13 +3,15 @@ public class SamplesSortedList { - public static void Main() + public static void Run() { // Creates and initializes a new SortedList. - SortedList mySortedList = new SortedList(); - mySortedList.Add("Third", "!"); - mySortedList.Add("Second", "World"); - mySortedList.Add("First", "Hello"); + SortedList mySortedList = new() + { + { "Third", "!" }, + { "Second", "World" }, + { "First", "Hello" } + }; // foreach (DictionaryEntry de in mySortedList) diff --git a/snippets/csharp/System.Collections/SortedList/Overview/source.cs b/snippets/csharp/System.Collections/SortedList/Overview/source.cs index 190de132c65..f49d2d56719 100644 --- a/snippets/csharp/System.Collections/SortedList/Overview/source.cs +++ b/snippets/csharp/System.Collections/SortedList/Overview/source.cs @@ -4,18 +4,20 @@ public class SamplesSortedList2 { - public static void Main() + public static void Run() { // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add("Third", "!"); - mySL.Add("Second", "World"); - mySL.Add("First", "Hello"); + SortedList mySL = new() + { + { "Third", "!" }, + { "Second", "World" }, + { "First", "Hello" } + }; // Displays the properties and values of the SortedList. Console.WriteLine("mySL"); - Console.WriteLine(" Count: {0}", mySL.Count); - Console.WriteLine(" Capacity: {0}", mySL.Capacity); + Console.WriteLine($" Count: {mySL.Count}"); + Console.WriteLine($" Capacity: {mySL.Capacity}"); Console.WriteLine(" Keys and Values:"); PrintKeysAndValues(mySL); } @@ -25,7 +27,7 @@ public static void PrintKeysAndValues(SortedList myList) Console.WriteLine("\t-KEY-\t-VALUE-"); for (int i = 0; i < myList.Count; i++) { - Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i)); + Console.WriteLine($"\t{myList.GetKey(i)}:\t{myList.GetByIndex(i)}"); } Console.WriteLine(); } diff --git a/snippets/csharp/System.Collections/SortedList/Remove/source.cs b/snippets/csharp/System.Collections/SortedList/Remove/source.cs index a5ac30dd3b5..37f9b7e8106 100644 --- a/snippets/csharp/System.Collections/SortedList/Remove/source.cs +++ b/snippets/csharp/System.Collections/SortedList/Remove/source.cs @@ -1,83 +1,89 @@ // - using System; - using System.Collections; - public class SamplesSortedList { +using System; +using System.Collections; +public class SamplesSortedList +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( "3c", "dog" ); - mySL.Add( "2c", "over" ); - mySL.Add( "1c", "brown" ); - mySL.Add( "1a", "The" ); - mySL.Add( "1b", "quick" ); - mySL.Add( "3a", "the" ); - mySL.Add( "3b", "lazy" ); - mySL.Add( "2a", "fox" ); - mySL.Add( "2b", "jumps" ); + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { "3c", "dog" }, + { "2c", "over" }, + { "1c", "brown" }, + { "1a", "The" }, + { "1b", "quick" }, + { "3a", "the" }, + { "3b", "lazy" }, + { "2a", "fox" }, + { "2b", "jumps" } + }; - // Displays the SortedList. - Console.WriteLine( "The SortedList initially contains the following:" ); - PrintKeysAndValues( mySL ); + // Displays the SortedList. + Console.WriteLine("The SortedList initially contains the following:"); + PrintKeysAndValues(mySL); - // Removes the element with the key "3b". - mySL.Remove( "3b" ); + // Removes the element with the key "3b". + mySL.Remove("3b"); - // Displays the current state of the SortedList. - Console.WriteLine( "After removing \"lazy\":" ); - PrintKeysAndValues( mySL ); + // Displays the current state of the SortedList. + Console.WriteLine("After removing \"lazy\":"); + PrintKeysAndValues(mySL); - // Removes the element at index 5. - mySL.RemoveAt( 5 ); + // Removes the element at index 5. + mySL.RemoveAt(5); - // Displays the current state of the SortedList. - Console.WriteLine( "After removing the element at index 5:" ); - PrintKeysAndValues( mySL ); + // Displays the current state of the SortedList. + Console.WriteLine("After removing the element at index 5:"); + PrintKeysAndValues(mySL); } - public static void PrintKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t{myList.GetKey(i)}:\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. +} +/* +This code produces the following output. - The SortedList initially contains the following: - -KEY- -VALUE- - 1a: The - 1b: quick - 1c: brown - 2a: fox - 2b: jumps - 2c: over - 3a: the - 3b: lazy - 3c: dog +The SortedList initially contains the following: + -KEY- -VALUE- + 1a: The + 1b: quick + 1c: brown + 2a: fox + 2b: jumps + 2c: over + 3a: the + 3b: lazy + 3c: dog - After removing "lazy": - -KEY- -VALUE- - 1a: The - 1b: quick - 1c: brown - 2a: fox - 2b: jumps - 2c: over - 3a: the - 3c: dog +After removing "lazy": + -KEY- -VALUE- + 1a: The + 1b: quick + 1c: brown + 2a: fox + 2b: jumps + 2c: over + 3a: the + 3c: dog - After removing the element at index 5: - -KEY- -VALUE- - 1a: The - 1b: quick - 1c: brown - 2a: fox - 2b: jumps - 3a: the - 3c: dog - */ - // +After removing the element at index 5: + -KEY- -VALUE- + 1a: The + 1b: quick + 1c: brown + 2a: fox + 2b: jumps + 3a: the + 3c: dog +*/ +// diff --git a/snippets/csharp/System.Collections/SortedList/SetByIndex/source.cs b/snippets/csharp/System.Collections/SortedList/SetByIndex/source.cs index 108037bbd56..2915afb3926 100644 --- a/snippets/csharp/System.Collections/SortedList/SetByIndex/source.cs +++ b/snippets/csharp/System.Collections/SortedList/SetByIndex/source.cs @@ -1,56 +1,62 @@ // - using System; - using System.Collections; - public class SamplesSortedList { - - public static void Main() { - - // Creates and initializes a new SortedList. - SortedList mySL = new SortedList(); - mySL.Add( 2, "two" ); - mySL.Add( 3, "three" ); - mySL.Add( 1, "one" ); - mySL.Add( 0, "zero" ); - mySL.Add( 4, "four" ); - - // Displays the values of the SortedList. - Console.WriteLine( "The SortedList contains the following values:" ); - PrintIndexAndKeysAndValues( mySL ); - - // Replaces the values at index 3 and index 4. - mySL.SetByIndex( 3, "III" ); - mySL.SetByIndex( 4, "IV" ); - - // Displays the updated values of the SortedList. - Console.WriteLine( "After replacing the value at index 3 and index 4," ); - PrintIndexAndKeysAndValues( mySL ); +using System; +using System.Collections; +public class SamplesSortedList +{ + + public static void Main() + { + + // Creates and initializes a new SortedList. + SortedList mySL = new() + { + { 2, "two" }, + { 3, "three" }, + { 1, "one" }, + { 0, "zero" }, + { 4, "four" } + }; + + // Displays the values of the SortedList. + Console.WriteLine("The SortedList contains the following values:"); + PrintIndexAndKeysAndValues(mySL); + + // Replaces the values at index 3 and index 4. + mySL.SetByIndex(3, "III"); + mySL.SetByIndex(4, "IV"); + + // Displays the updated values of the SortedList. + Console.WriteLine("After replacing the value at index 3 and index 4,"); + PrintIndexAndKeysAndValues(mySL); } - public static void PrintIndexAndKeysAndValues( SortedList myList ) { - Console.WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" ); - for ( int i = 0; i < myList.Count; i++ ) { - Console.WriteLine( "\t[{0}]:\t{1}\t{2}", i, myList.GetKey(i), myList.GetByIndex(i) ); - } - Console.WriteLine(); + public static void PrintIndexAndKeysAndValues(SortedList myList) + { + Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-"); + for (int i = 0; i < myList.Count; i++) + { + Console.WriteLine($"\t[{i}]:\t{myList.GetKey(i)}\t{myList.GetByIndex(i)}"); + } + Console.WriteLine(); } - } - /* - This code produces the following output. - - The SortedList contains the following values: - -INDEX- -KEY- -VALUE- - [0]: 0 zero - [1]: 1 one - [2]: 2 two - [3]: 3 three - [4]: 4 four - - After replacing the value at index 3 and index 4, - -INDEX- -KEY- -VALUE- - [0]: 0 zero - [1]: 1 one - [2]: 2 two - [3]: 3 III - [4]: 4 IV - */ - // +} +/* +This code produces the following output. + +The SortedList contains the following values: + -INDEX- -KEY- -VALUE- + [0]: 0 zero + [1]: 1 one + [2]: 2 two + [3]: 3 three + [4]: 4 four + +After replacing the value at index 3 and index 4, + -INDEX- -KEY- -VALUE- + [0]: 0 zero + [1]: 1 one + [2]: 2 two + [3]: 3 III + [4]: 4 IV +*/ +// diff --git a/snippets/csharp/System.Collections/Stack/Clear/source.cs b/snippets/csharp/System.Collections/Stack/Clear/source.cs index 05bed220b74..ef1b2572685 100644 --- a/snippets/csharp/System.Collections/Stack/Clear/source.cs +++ b/snippets/csharp/System.Collections/Stack/Clear/source.cs @@ -1,52 +1,58 @@ // - using System; - using System.Collections; - - public class SamplesStack { - - public static void Main() { - - // Creates and initializes a new Stack. - Stack myStack = new Stack(); - myStack.Push( "The" ); - myStack.Push( "quick" ); - myStack.Push( "brown" ); - myStack.Push( "fox" ); - myStack.Push( "jumps" ); - - // Displays the count and values of the Stack. - Console.WriteLine( "Initially," ); - Console.WriteLine( " Count : {0}", myStack.Count ); - Console.Write( " Values:" ); - PrintValues( myStack ); - - // Clears the Stack. - myStack.Clear(); - - // Displays the count and values of the Stack. - Console.WriteLine( "After Clear," ); - Console.WriteLine( " Count : {0}", myStack.Count ); - Console.Write( " Values:" ); - PrintValues( myStack ); +using System; +using System.Collections; + +public class SamplesStack +{ + + public static void Main() + { + + // Creates and initializes a new Stack. + Stack myStack = new(); + myStack.Push("The"); + myStack.Push("quick"); + myStack.Push("brown"); + myStack.Push("fox"); + myStack.Push("jumps"); + + // Displays the count and values of the Stack. + Console.WriteLine("Initially,"); + Console.WriteLine($" Count : {myStack.Count}"); + Console.Write(" Values:"); + PrintValues(myStack); + + // Clears the Stack. + myStack.Clear(); + + // Displays the count and values of the Stack. + Console.WriteLine("After Clear,"); + Console.WriteLine($" Count : {myStack.Count}"); + Console.Write(" Values:"); + PrintValues(myStack); } - public static void PrintValues( IEnumerable myCollection ) { - foreach ( Object obj in myCollection ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myCollection) + { + foreach (object obj in myCollection) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Initially, - Count : 5 - Values: jumps fox brown quick The - After Clear, - Count : 0 - Values: - */ +Initially, + Count : 5 + Values: jumps fox brown quick The +After Clear, + Count : 0 + Values: +*/ - // +// diff --git a/snippets/csharp/System.Collections/Stack/CopyTo/source.cs b/snippets/csharp/System.Collections/Stack/CopyTo/source.cs index 16c48d43e90..2309cb715c9 100644 --- a/snippets/csharp/System.Collections/Stack/CopyTo/source.cs +++ b/snippets/csharp/System.Collections/Stack/CopyTo/source.cs @@ -1,66 +1,70 @@ -// - using System; - using System.Collections; - public class SamplesStack { +// +using System; +using System.Collections; +public class SamplesStack +{ - public static void Main() { + public static void Main() + { - // Creates and initializes the source Stack. - Stack mySourceQ = new Stack(); - mySourceQ.Push( "barn" ); - mySourceQ.Push( "the" ); - mySourceQ.Push( "in" ); - mySourceQ.Push( "cats" ); - mySourceQ.Push( "napping" ); - mySourceQ.Push( "three" ); + // Creates and initializes the source Stack. + Stack mySourceQ = new(); + mySourceQ.Push("barn"); + mySourceQ.Push("the"); + mySourceQ.Push("in"); + mySourceQ.Push("cats"); + mySourceQ.Push("napping"); + mySourceQ.Push("three"); - // Creates and initializes the one-dimensional target Array. - Array myTargetArray=Array.CreateInstance( typeof(string), 15 ); - myTargetArray.SetValue( "The", 0 ); - myTargetArray.SetValue( "quick", 1 ); - myTargetArray.SetValue( "brown", 2 ); - myTargetArray.SetValue( "fox", 3 ); - myTargetArray.SetValue( "jumps", 4 ); - myTargetArray.SetValue( "over", 5 ); - myTargetArray.SetValue( "the", 6 ); - myTargetArray.SetValue( "lazy", 7 ); - myTargetArray.SetValue( "dog", 8 ); + // Creates and initializes the one-dimensional target Array. + Array myTargetArray = Array.CreateInstance(typeof(string), 15); + myTargetArray.SetValue("The", 0); + myTargetArray.SetValue("quick", 1); + myTargetArray.SetValue("brown", 2); + myTargetArray.SetValue("fox", 3); + myTargetArray.SetValue("jumps", 4); + myTargetArray.SetValue("over", 5); + myTargetArray.SetValue("the", 6); + myTargetArray.SetValue("lazy", 7); + myTargetArray.SetValue("dog", 8); - // Displays the values of the target Array. - Console.WriteLine( "The target Array contains the following (before and after copying):" ); - PrintValues( myTargetArray, ' ' ); + // Displays the values of the target Array. + Console.WriteLine("The target Array contains the following (before and after copying):"); + PrintValues(myTargetArray, ' '); - // Copies the entire source Stack to the target Array, starting at index 6. - mySourceQ.CopyTo( myTargetArray, 6 ); + // Copies the entire source Stack to the target Array, starting at index 6. + mySourceQ.CopyTo(myTargetArray, 6); - // Displays the values of the target Array. - PrintValues( myTargetArray, ' ' ); + // Displays the values of the target Array. + PrintValues(myTargetArray, ' '); - // Copies the entire source Stack to a new standard array. - Object[] myStandardArray = mySourceQ.ToArray(); + // Copies the entire source Stack to a new standard array. + object[] myStandardArray = mySourceQ.ToArray(); - // Displays the values of the new standard array. - Console.WriteLine( "The new standard array contains the following:" ); - PrintValues( myStandardArray, ' ' ); + // Displays the values of the new standard array. + Console.WriteLine("The new standard array contains the following:"); + PrintValues(myStandardArray, ' '); } - public static void PrintValues( Array myArr, char mySeparator ) { - foreach ( Object myObj in myArr ) { - Console.Write( "{0}{1}", mySeparator, myObj ); - } - Console.WriteLine(); + public static void PrintValues(Array myArr, char mySeparator) + { + foreach (object myObj in myArr) + { + Console.Write($"{mySeparator}{myObj}"); + } + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - The target Array contains the following (before and after copying): - The quick brown fox jumps over the lazy dog - The quick brown fox jumps over three napping cats in the barn - The new standard array contains the following: - three napping cats in the barn - */ +The target Array contains the following (before and after copying): + The quick brown fox jumps over the lazy dog + The quick brown fox jumps over three napping cats in the barn +The new standard array contains the following: + three napping cats in the barn +*/ - // +// diff --git a/snippets/csharp/System.Collections/Stack/IsSynchronized/Program.cs b/snippets/csharp/System.Collections/Stack/IsSynchronized/Program.cs new file mode 100644 index 00000000000..0ae007cdd2c --- /dev/null +++ b/snippets/csharp/System.Collections/Stack/IsSynchronized/Program.cs @@ -0,0 +1,2 @@ +SamplesStack.Run(); +SamplesStack2.Run(); diff --git a/snippets/csharp/System.Collections/Stack/IsSynchronized/Project.csproj b/snippets/csharp/System.Collections/Stack/IsSynchronized/Project.csproj index 921d2f7be37..ffb97e9872d 100644 --- a/snippets/csharp/System.Collections/Stack/IsSynchronized/Project.csproj +++ b/snippets/csharp/System.Collections/Stack/IsSynchronized/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - SamplesStack \ No newline at end of file diff --git a/snippets/csharp/System.Collections/Stack/IsSynchronized/source.cs b/snippets/csharp/System.Collections/Stack/IsSynchronized/source.cs index 723467c2918..bd341aa2e41 100644 --- a/snippets/csharp/System.Collections/Stack/IsSynchronized/source.cs +++ b/snippets/csharp/System.Collections/Stack/IsSynchronized/source.cs @@ -4,10 +4,10 @@ public class SamplesStack { - public static void Main() + public static void Run() { // Creates and initializes a new Stack. - Stack myStack = new Stack(); + Stack myStack = new(); myStack.Push("The"); myStack.Push("quick"); myStack.Push("brown"); @@ -17,10 +17,8 @@ public static void Main() Stack mySyncdStack = Stack.Synchronized(myStack); // Displays the sychronization status of both Stacks. - Console.WriteLine("myStack is {0}.", - myStack.IsSynchronized ? "synchronized" : "not synchronized"); - Console.WriteLine("mySyncdStack is {0}.", - mySyncdStack.IsSynchronized ? "synchronized" : "not synchronized"); + Console.WriteLine($"myStack is {(myStack.IsSynchronized ? "synchronized" : "not synchronized")}."); + Console.WriteLine($"mySyncdStack is {(mySyncdStack.IsSynchronized ? "synchronized" : "not synchronized")}."); } } /* diff --git a/snippets/csharp/System.Collections/Stack/IsSynchronized/source2.cs b/snippets/csharp/System.Collections/Stack/IsSynchronized/source2.cs index edb119808cf..8a1f933e658 100644 --- a/snippets/csharp/System.Collections/Stack/IsSynchronized/source2.cs +++ b/snippets/csharp/System.Collections/Stack/IsSynchronized/source2.cs @@ -3,10 +3,10 @@ public class SamplesStack2 { - public static void Main() + public static void Run() { // - Stack myCollection = new Stack(); + Stack myCollection = new(); lock (myCollection.SyncRoot) { diff --git a/snippets/csharp/System.Collections/Stack/Overview/source.cs b/snippets/csharp/System.Collections/Stack/Overview/source.cs index 51537d2dd46..7b49406526e 100644 --- a/snippets/csharp/System.Collections/Stack/Overview/source.cs +++ b/snippets/csharp/System.Collections/Stack/Overview/source.cs @@ -1,37 +1,43 @@ // - using System; - using System.Collections; - public class SamplesStack { - - public static void Main() { - - // Creates and initializes a new Stack. - Stack myStack = new Stack(); - myStack.Push("Hello"); - myStack.Push("World"); - myStack.Push("!"); - - // Displays the properties and values of the Stack. - Console.WriteLine( "myStack" ); - Console.WriteLine( "\tCount: {0}", myStack.Count ); - Console.Write( "\tValues:" ); - PrintValues( myStack ); +using System; +using System.Collections; +public class SamplesStack +{ + + public static void Main() + { + + // Creates and initializes a new Stack. + Stack myStack = new(); + myStack.Push("Hello"); + myStack.Push("World"); + myStack.Push("!"); + + // Displays the properties and values of the Stack. + Console.WriteLine("myStack"); + Console.WriteLine($"\tCount: {myStack.Count}"); + Console.Write("\tValues:"); + PrintValues(myStack); } - public static void PrintValues( IEnumerable myCollection ) { - foreach ( Object obj in myCollection ) - Console.Write( " {0}", obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myCollection) + { + foreach (object obj in myCollection) + { + Console.Write($" {obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - myStack - Count: 3 - Values: ! World Hello - */ +myStack + Count: 3 + Values: ! World Hello +*/ // diff --git a/snippets/csharp/System.Collections/Stack/Peek/source.cs b/snippets/csharp/System.Collections/Stack/Peek/source.cs index a8dc1db9349..59ccddb8c36 100644 --- a/snippets/csharp/System.Collections/Stack/Peek/source.cs +++ b/snippets/csharp/System.Collections/Stack/Peek/source.cs @@ -1,61 +1,67 @@ // - using System; - using System.Collections; - public class SamplesStack { +using System; +using System.Collections; +public class SamplesStack +{ - public static void Main() { + public static void Main() + { - // Creates and initializes a new Stack. - Stack myStack = new Stack(); - myStack.Push( "The" ); - myStack.Push( "quick" ); - myStack.Push( "brown" ); - myStack.Push( "fox" ); + // Creates and initializes a new Stack. + Stack myStack = new(); + myStack.Push("The"); + myStack.Push("quick"); + myStack.Push("brown"); + myStack.Push("fox"); - // Displays the Stack. - Console.Write( "Stack values:" ); - PrintValues( myStack, '\t' ); + // Displays the Stack. + Console.Write("Stack values:"); + PrintValues(myStack, '\t'); - // Removes an element from the Stack. - Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() ); + // Removes an element from the Stack. + Console.WriteLine($"(Pop)\t\t{myStack.Pop()}"); - // Displays the Stack. - Console.Write( "Stack values:" ); - PrintValues( myStack, '\t' ); + // Displays the Stack. + Console.Write("Stack values:"); + PrintValues(myStack, '\t'); - // Removes another element from the Stack. - Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() ); + // Removes another element from the Stack. + Console.WriteLine($"(Pop)\t\t{myStack.Pop()}"); - // Displays the Stack. - Console.Write( "Stack values:" ); - PrintValues( myStack, '\t' ); + // Displays the Stack. + Console.Write("Stack values:"); + PrintValues(myStack, '\t'); - // Views the first element in the Stack but does not remove it. - Console.WriteLine( "(Peek)\t\t{0}", myStack.Peek() ); + // Views the first element in the Stack but does not remove it. + Console.WriteLine($"(Peek)\t\t{myStack.Peek()}"); - // Displays the Stack. - Console.Write( "Stack values:" ); - PrintValues( myStack, '\t' ); + // Displays the Stack. + Console.Write("Stack values:"); + PrintValues(myStack, '\t'); } - public static void PrintValues( IEnumerable myCollection, char mySeparator ) { - foreach ( Object obj in myCollection ) - Console.Write( "{0}{1}", mySeparator, obj ); - Console.WriteLine(); + public static void PrintValues(IEnumerable myCollection, char mySeparator) + { + foreach (object obj in myCollection) + { + Console.Write($"{mySeparator}{obj}"); + } + + Console.WriteLine(); } - } +} - /* - This code produces the following output. +/* +This code produces the following output. - Stack values: fox brown quick The - (Pop) fox - Stack values: brown quick The - (Pop) brown - Stack values: quick The - (Peek) quick - Stack values: quick The - */ +Stack values: fox brown quick The +(Pop) fox +Stack values: brown quick The +(Pop) brown +Stack values: quick The +(Peek) quick +Stack values: quick The +*/ - // +// diff --git a/xml/Microsoft.Extensions.Hosting/HostApplicationBuilder.xml b/xml/Microsoft.Extensions.Hosting/HostApplicationBuilder.xml index daf86301ee5..3a1f631a4cc 100644 --- a/xml/Microsoft.Extensions.Hosting/HostApplicationBuilder.xml +++ b/xml/Microsoft.Extensions.Hosting/HostApplicationBuilder.xml @@ -59,7 +59,7 @@ The following defaults are applied to the returned : - set the to the result of load host from "DOTNET_" prefixed environment variablesload host from supplied command line argsload app from 'appsettings.json' and 'appsettings.[].json'load app from '[].settings.json' and '[].settings.[].json' when is not emptyload app from User Secrets when is 'Development' using the entry assemblyload app from environment variablesload app from supplied command line argsconfigure the to log to the console, debug, and event source outputenables scope validation on the dependency injection container when is 'Development' + set the to the result of load host from "DOTNET_" prefixed environment variablesload app from 'appsettings.json' and 'appsettings.[].json'load app from '[].settings.json' and '[].settings.[].json' when is not emptyload app from User Secrets when is 'Development' using the entry assemblyload app from environment variablesconfigure the to log to the console, debug, and event source outputenables scope validation on the dependency injection container when is 'Development' diff --git a/xml/System.Buffers/SearchValues.xml b/xml/System.Buffers/SearchValues.xml index f85c9422d39..77d4222278e 100644 --- a/xml/System.Buffers/SearchValues.xml +++ b/xml/System.Buffers/SearchValues.xml @@ -19,7 +19,18 @@ Provides a set of initialization methods for instances of the class. - instances are optimized for situations where the same set of values is frequently used for searching at run time. + instances are optimized for situations where the same set of values is frequently used for searching at run time. Creating an instance is relatively expensive because the values are analyzed to pick a specialized, often vectorized, search algorithm. Create the instance once and cache it, typically in a `static readonly` field, then pass it to the methods that search a span, such as , , , and . + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetEscaping"::: + +For more use cases and examples, see . + +]]> + @@ -70,7 +81,17 @@ The set of values. Creates an optimized representation of used for efficient searching. The optimized representation of used for efficient searching. - To be added. + + overloads that accept individual values only go up to three: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetBytes"::: + +]]> + @@ -116,7 +137,17 @@ The set of values. Creates an optimized representation of used for efficient searching. The optimized representation of used for efficient searching. - To be added. + + + @@ -152,7 +183,23 @@ Specifies whether to use or search semantics. Creates an optimized representation of used for efficient searching. The optimized representation of used for efficient searching. - Only or may be used. + + or can be used. + +The returned instance searches for whole substrings, so it can only be used with the and overloads that accept a `SearchValues`. If you're searching for individual characters, use instead. + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetStrings"::: + +Passing a single value is also useful. The resulting instance is a faster alternative to , because the value is analyzed when the instance is created instead of on every search: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetSingleString"::: + +]]> + diff --git a/xml/System.Buffers/SearchValues`1.xml b/xml/System.Buffers/SearchValues`1.xml index 64601241712..583faf47cb0 100644 --- a/xml/System.Buffers/SearchValues`1.xml +++ b/xml/System.Buffers/SearchValues`1.xml @@ -26,9 +26,61 @@ The type of the values to search for. Provides an immutable, read-only set of values optimized for efficient searching. - Instances are created by or . + Instances are created by , , or . - instances are optimized for situations where the same set of values is frequently used for searching at run time. + instances are optimized for situations where the same set of values is frequently used for searching at run time. When you create the instance, the runtime analyzes the values and picks a search algorithm that's specialized for that set, often using vectorized (SIMD) instructions. That analysis is done once, so create the instance once and cache it, typically in a `static readonly` field. + +Passing a to one of the searching methods on is usually much faster than passing the values as a span, especially for larger sets of values. Searching a span for a set of values is the primary purpose of the type, so reach for the following methods first: + +| Method | Use it to | +|--|--| +| | Find the first position of any of the values. | +| | Find the first position of anything that isn't one of the values. | +| / | Search backwards for the same conditions. | +| / | Test whether a span contains any of the values, or anything other than the values. | +| | Count how many elements in the span are in the set. | +| / | Replace the elements that are (or aren't) in the set. | +| | Split a span on any of the values. | + +## Common use cases + +Validation is one. Instead of testing each element in a loop, describe the set of allowed values once and use to find out whether the input contains anything else: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetValidation"::: + +Escaping and encoding are another. Use to skip ahead to the next element that needs special treatment, so that everything in between is processed in bulk: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetEscaping"::: + +The same applies to UTF-8 data. Create a of from a UTF-8 literal to search the bytes without transcoding them first. The benefit grows with the number of values: the overloads that take individual values only go up to three, and passing a longer span of values is slower than using a cached : + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetBytes"::: + +Starting in .NET 9, you can also search for a set of substrings by creating a of with . Such an instance can only be used with the and overloads that accept a `SearchValues`: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetStrings"::: + +You can also create such an instance from a single string. Doing so is a faster alternative to , because the value is analyzed when the instance is created instead of on every search: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetSingleString"::: + +## Thread safety + + is immutable and all of its members are thread-safe, so a single cached instance can be shared across the whole app. + +]]> + + + + + + + + @@ -57,7 +109,29 @@ Searches for the specified value. if was found; otherwise, . - To be added. + + . The type is designed to search a whole span at once, so prefer the methods that accept a , such as , , , or . Those methods can process many elements at a time, whereas calling `Contains` in a loop can't. + +Use this method when you only have a single value at hand and there's no span to search, for example: + +- You're inspecting or producing elements one at a time as part of a larger operation, such as decoding, transcoding, or transforming each element. +- You've already located an element with one of the searching methods and want to classify the element that follows it. +- You want to reuse an existing set of values as a general-purpose lookup table for a value you got from somewhere else. + +The following example turns `\uXXXX` escape sequences back into the characters they represent, but leaves the ones that must stay escaped alone. Because each decoded character is computed on the fly, there's no span to search and `Contains` is the appropriate choice: + +:::code language="csharp" source="~/snippets/csharp/System.Buffers/SearchValues/Overview/searchvalues.cs" id="SnippetContains"::: + +For a of , this method tests whether the whole `value` is one of the strings in the set, using the that was specified when the instance was created. It doesn't perform a substring search. Such a lookup is slower than , so only create a of when you need to search a span for multiple substrings. + +]]> + + + diff --git a/xml/System.CodeDom.Compiler/CodeDomProvider.xml b/xml/System.CodeDom.Compiler/CodeDomProvider.xml index e15074b4da3..5685979c18c 100644 --- a/xml/System.CodeDom.Compiler/CodeDomProvider.xml +++ b/xml/System.CodeDom.Compiler/CodeDomProvider.xml @@ -51,9 +51,9 @@ The class provides static methods to discover and enumerate the implementations on a computer. The method returns the settings for all implementations on a computer. The method returns the settings for a specific implementation, based on the programming language name. The method returns an instance of a implementation for a specific language. ## Examples - The following example program can generate and compile source code based on a CodeDOM model of a program that prints "Hello World" using the class. A Windows Forms user interface is provided. The user can select the target programming language from several selections: C#, Visual Basic, and JScript. + The following example program generates source code based on a CodeDOM model of a program that prints "Hello World" using the class. A Windows Forms user interface is provided. The user can select C# or Visual Basic as the target programming language. - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs" id="Snippet1"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet3"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeCompileUnit/Overview/source.vb" id="Snippet1"::: ]]> @@ -838,7 +838,7 @@ ## Examples The following code example shows the use of the method to generate code for a "Hello World" application from a . This example is part of a larger example provided for the class. - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs" id="Snippet3"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet6"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeCompileUnit/Overview/source.vb" id="Snippet3"::: ]]> diff --git a/xml/System.CodeDom/CodeArrayCreateExpression.xml b/xml/System.CodeDom/CodeArrayCreateExpression.xml index 199757f270e..e6529c084e8 100644 --- a/xml/System.CodeDom/CodeArrayCreateExpression.xml +++ b/xml/System.CodeDom/CodeArrayCreateExpression.xml @@ -37,13 +37,11 @@ can be used to represent a code expression that creates an array. Expressions that create an array should specify either a number of elements, or a list of expressions to use to initialize the array. + can be used to represent a code expression that creates an array. Expressions that create an array should specify either a number of elements or a list of expressions to use to initialize the array. Most arrays can be initialized immediately following declaration. The property can be set to the expression to use to initialize the array. - A only directly supports creating single-dimension arrays. If a language allows arrays of arrays, it is possible to create them by nesting a within a . Not all languages support arrays of arrays. You can check whether an for a language declares support for nested arrays by calling with the flag. - - + A only directly supports creating single-dimension arrays. If a language allows arrays of arrays, it's possible to create them by nesting a within a . Not all languages support arrays of arrays. You can check whether an for a language declares support for nested arrays by calling with the flag. ## Examples The following code uses a to create an array of integers with 10 indexes. @@ -583,14 +581,7 @@ Gets or sets the expression that indicates the size of the array. A that indicates the size of the array. - - . - - ]]> - + The size of the array can be represented with a . diff --git a/xml/System.CodeDom/CodeArrayIndexerExpression.xml b/xml/System.CodeDom/CodeArrayIndexerExpression.xml index 78f131a6d5b..eb6a0721d57 100644 --- a/xml/System.CodeDom/CodeArrayIndexerExpression.xml +++ b/xml/System.CodeDom/CodeArrayIndexerExpression.xml @@ -39,12 +39,10 @@ ## Remarks can be used to represent a reference to an index of an array of one or more dimensions. Use for representing a reference to an index of a code (non-array) indexer. The property indicates the indexer object. The property indicates either a single index within the target array, or a set of indexes that together specify a specific intersection of indexes across the dimensions of the array. - - ## Examples - The following code creates a that references index 5 of an array of integers named `x` : + The following code creates a that references index 5 of an array of integers named `x`: - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayIndexerExpression/Overview/codearrayindexerexpressionsnippet.cs" id="Snippet1"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeArrayIndexerExpression/Overview/codearrayindexerexpressionsnippet.vb" id="Snippet1"::: ]]> diff --git a/xml/System.CodeDom/CodeAssignStatement.xml b/xml/System.CodeDom/CodeAssignStatement.xml index 2cda66a5b94..3a4f5964ccb 100644 --- a/xml/System.CodeDom/CodeAssignStatement.xml +++ b/xml/System.CodeDom/CodeAssignStatement.xml @@ -44,7 +44,7 @@ ## Examples The following code creates a that assigns the value 10 to an integer variable named `i`: - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeAssignStatement/Overview/codeassignstatementsnippet.cs" id="Snippet1"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeAssignStatement/Overview/codeassignstatementsnippet.vb" id="Snippet1"::: ]]> diff --git a/xml/System.CodeDom/CodeChecksumPragma.xml b/xml/System.CodeDom/CodeChecksumPragma.xml index a62b1bc6579..068643f83a3 100644 --- a/xml/System.CodeDom/CodeChecksumPragma.xml +++ b/xml/System.CodeDom/CodeChecksumPragma.xml @@ -86,10 +86,10 @@ constructor. This code example is part of a larger example provided for the class. - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeChecksumPragma/Overview/codedirective.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeChecksumPragma/Overview/codedirective.vb" id="Snippet4"::: +The following code example shows the use of the constructor. This code example is part of a larger example provided for the class. + +:::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeChecksumPragma/Overview/codedirective.vb" id="Snippet4"::: ]]> diff --git a/xml/System.CodeDom/CodeCompileUnit.xml b/xml/System.CodeDom/CodeCompileUnit.xml index 5f63bf6a116..e8d979930b3 100644 --- a/xml/System.CodeDom/CodeCompileUnit.xml +++ b/xml/System.CodeDom/CodeCompileUnit.xml @@ -51,7 +51,7 @@ ## Examples The following code example constructs a that models the program structure of a simple "Hello World" program. This code example is part of a larger example that also produces code from this model, and is provided for the class. - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs" id="Snippet2"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet2"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeCompileUnit/Overview/source.vb" id="Snippet2"::: ]]> @@ -221,7 +221,7 @@ ## Examples The following code example constructs a that models the program structure of a simple "Hello World" program. This example is part of a larger example that also produces code from this model, and is provided for the class. - :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeCompileUnit/Overview/source.cs" id="Snippet2"::: + :::code language="csharp" source="~/snippets/csharp/System.CodeDom/CodeArrayCreateExpression/Overview/codearraycreateexpressionsnippet.cs" id="Snippet2"::: :::code language="vb" source="~/snippets/visualbasic/System.CodeDom/CodeCompileUnit/Overview/source.vb" id="Snippet2"::: ]]> diff --git a/xml/System.Runtime.Versioning/OSPlatformAttribute.xml b/xml/System.Runtime.Versioning/OSPlatformAttribute.xml index 3222d064f16..067bc4edc03 100644 --- a/xml/System.Runtime.Versioning/OSPlatformAttribute.xml +++ b/xml/System.Runtime.Versioning/OSPlatformAttribute.xml @@ -28,6 +28,7 @@ Base type for all platform-specific API attributes. To be added. + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.xml b/xml/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.xml index 31eabc1c13f..235d925b4be 100644 --- a/xml/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.xml +++ b/xml/System.Runtime.Versioning/ObsoletedOSPlatformAttribute.xml @@ -30,6 +30,7 @@ Marks APIs that were obsoleted in a given operating system version. Primarily used by OS bindings to indicate APIs that should not be used anymore. + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/SupportedOSPlatformAttribute.xml b/xml/System.Runtime.Versioning/SupportedOSPlatformAttribute.xml index 81febb441ae..430ee7a6b26 100644 --- a/xml/System.Runtime.Versioning/SupportedOSPlatformAttribute.xml +++ b/xml/System.Runtime.Versioning/SupportedOSPlatformAttribute.xml @@ -37,6 +37,7 @@ Callers can apply a + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.xml b/xml/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.xml index 472899a5abb..2327b7394ff 100644 --- a/xml/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.xml +++ b/xml/System.Runtime.Versioning/SupportedOSPlatformGuardAttribute.xml @@ -39,6 +39,7 @@ Callers can apply a + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/TargetPlatformAttribute.xml b/xml/System.Runtime.Versioning/TargetPlatformAttribute.xml index dee82207d44..0eb03f8cc4c 100644 --- a/xml/System.Runtime.Versioning/TargetPlatformAttribute.xml +++ b/xml/System.Runtime.Versioning/TargetPlatformAttribute.xml @@ -28,6 +28,7 @@ Specifies the operating system that a project targets, for example, Windows or iOS. To be added. + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.xml b/xml/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.xml index 00ea7b83edb..4962d0acc66 100644 --- a/xml/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.xml +++ b/xml/System.Runtime.Versioning/UnsupportedOSPlatformAttribute.xml @@ -40,6 +40,7 @@ The versionless attribute is primarily used to indicate the API is unsupported f ]]> + Platform compatibility analyzer diff --git a/xml/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.xml b/xml/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.xml index 3575beb55d6..41c66fad4df 100644 --- a/xml/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.xml +++ b/xml/System.Runtime.Versioning/UnsupportedOSPlatformGuardAttribute.xml @@ -39,6 +39,7 @@ Callers can apply a + Platform compatibility analyzer diff --git a/xml/System/OperatingSystem.xml b/xml/System/OperatingSystem.xml index 621464c1801..94d2aede313 100644 --- a/xml/System/OperatingSystem.xml +++ b/xml/System/OperatingSystem.xml @@ -83,6 +83,7 @@ ]]> + Platform compatibility analyzer