diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1045.md b/docs/fundamentals/code-analysis/quality-rules/ca1045.md index 6c3636aa9d513..c142af836bef6 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1045.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1045.md @@ -31,18 +31,18 @@ Passing types by reference (using `out` or `ref`) requires experience with point When a reference type is passed "by reference," the method intends to use the parameter to return a different instance of the object. (Passing a reference type by reference is also known as using a double pointer, pointer to a pointer, or double indirection.) Using the default calling convention, which is pass "by value," a parameter that takes a reference type already receives a pointer to the object. The pointer, not the object to which it points, is passed by value. Passing by value means that the method cannot change the pointer to have it point to a new instance of the reference type, but can change the contents of the object to which it points. For most applications this is sufficient and yields the behavior that you want. -If a method must return a different instance, use the return value of the method to accomplish this. See the class for a variety of methods that operate on strings and return a new instance of a string. By using this model, it is left to the caller to decide whether the original object is preserved. +If a method must return a different instance, use the return value of the method to accomplish this. For methods that operate on strings and return a new instance of a string, see the class. By using this model, it is left to the caller to decide whether the original object is preserved. Although return values are commonplace and heavily used, the correct application of `out` and `ref` parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to become proficient in working with `out` or `ref` parameters. > [!NOTE] -> When you work with parameters that are large structures, the additional resources that are required to copy these structures could cause a performance effect when you pass by value. In these cases, you might consider using `ref` or `out` parameters. +> When you work with parameters that are large structures, the additional resources that are required to copy these structures could have a performance effect when you pass by value. In these cases, you might consider using `ref` or `out` parameters. ## How to fix violations -To fix a violation of this rule that is caused by a value type, have the method return the object as its return value. If the method must return multiple values, redesign it to return a single instance of an object that holds the values. +To fix a violation of this rule that's caused by a value type, have the method return the object as its return value. If the method must return multiple values, redesign it to return a single instance of an object that holds the values. -To fix a violation of this rule that is caused by a reference type, make sure that the behavior that you want is to return a new instance of the reference. If it is, the method should use its return value to do this. +To fix a violation of this rule that's caused by a reference type, make sure that the behavior that you want is to return a new instance of the reference. If it is, the method should use its return value to do this. ## When to suppress warnings diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1806.md b/docs/fundamentals/code-analysis/quality-rules/ca1806.md index 3a2fa43a3af4b..cb34fc9d91d65 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1806.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1806.md @@ -30,8 +30,8 @@ There are several possible reasons for this warning: - A new object is created but never used. - A method that creates and returns a new string is called and the new string is never used. -- A COM or P/Invoke method that returns a `HRESULT` or error code that's never used. -- A language-integrated query (LINQ) method that returns a result that's never used. +- A COM or P/Invoke method returns a `HRESULT` or error code that's never used. +- A language-integrated query (LINQ) method returns a result that's never used. ## Rule description @@ -110,33 +110,22 @@ dotnet_code_quality.CA1806.additional_use_results_methods = M:MyNamespace.MyType The following example shows a class that ignores the result of calling . :::code language="csharp" source="snippets/csharp/all-rules/ca1806.cs" id="snippet1"::: - :::code language="vb" source="snippets/vb/all-rules/ca1806-do-not-ignore-method-results_1.vb" id="snippet1"::: -## Example 2 - -The following example fixes the [Example 1](#example-1) violation by assigning the result of back to the variable it was called on. +The following example fixes the violation by assigning the result of back to the variable it was called on. :::code language="csharp" source="snippets/csharp/all-rules/ca1806.cs" id="snippet2"::: - :::code language="vb" source="snippets/vb/all-rules/ca1806-do-not-ignore-method-results_1.vb" id="snippet2"::: -## Example 3 +## Example 2 -The following example shows a method that does not use an object that it creates. +The following example shows a method that doesn't use an object that it creates. > [!NOTE] > This violation cannot be reproduced in Visual Basic. :::code language="csharp" source="snippets/csharp/all-rules/ca1806.cs" id="snippet3"::: -## Example 4 - -The following example fixes the [Example 3](#example-3) violation by removing the unnecessary creation of an object. +The following example fixes the violation by removing the unnecessary creation of an object. :::code language="csharp" source="snippets/csharp/all-rules/ca1806.cs" id="snippet4"::: - - diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1816.md b/docs/fundamentals/code-analysis/quality-rules/ca1816.md index 07f6bf5e2ca7b..1e8d6d9a9530e 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1816.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1816.md @@ -36,7 +36,7 @@ Violations of this rule can be caused by: ## Rule description -The method lets users release resources at any time before the object becoming available for garbage collection. If the method is called, it frees resources of the object. This makes finalization unnecessary. should call so the garbage collector doesn't call the finalizer of the object. +The method lets users release resources at any time before the object becomes available for garbage collection. If the method is called, it frees resources of the object. This makes finalization unnecessary. should call so the garbage collector doesn't call the finalizer of the object. To prevent derived types with finalizers from having to reimplement and to call it, unsealed types without finalizers should still call . diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2100.md b/docs/fundamentals/code-analysis/quality-rules/ca2100.md index b895770a83559..b8c91a24e89f5 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2100.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2100.md @@ -1,7 +1,7 @@ --- title: "CA2100: Review SQL queries for security vulnerabilities (code analysis)" description: "Learn about code analysis rule CA2100: Review SQL queries for security vulnerabilities" -ms.date: 11/04/2016 +ms.date: 09/24/2025 f1_keywords: - Review SQL queries for security vulnerabilities - ReviewSqlQueriesForSecurityVulnerabilities @@ -37,7 +37,7 @@ This rule assumes that any string whose value can't be determined at compile tim - Use a parameterized command string. - Validate the user input for both type and content before you build the command string. -The following .NET types implement the property or provide constructors that set the property by using a string argument. +The following .NET types implement the property or provide constructors that set the property by using a string argument: - and - and @@ -64,7 +64,7 @@ To fix a violation of this rule, use a parameterized query. ## When to suppress warnings -It is safe to suppress a warning from this rule if the command text does not contain any user input. +It's safe to suppress a warning from this rule if the command text does not contain any user input. ## Suppress a warning diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2235.md b/docs/fundamentals/code-analysis/quality-rules/ca2235.md index c78e2eb1ac1b0..4263fab2efcb3 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2235.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2235.md @@ -67,7 +67,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w The following example shows two types: one that violates the rule and one that satisfies the rule. :::code language="csharp" source="snippets/csharp/all-rules/ca2235.cs" id="snippet1"::: - :::code language="vb" source="snippets/vb/all-rules/ca2235-mark-all-non-serializable-fields_1.vb"::: ## Remarks diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/.editorconfig b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/.editorconfig index 328b08ee34f0b..4edc25e7a4f19 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/.editorconfig +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/.editorconfig @@ -17,3 +17,6 @@ dotnet_diagnostic.CA1822.severity = none # CA2200: Rethrow to preserve stack details dotnet_diagnostic.CA2200.severity = suggestion + +# CA2100 +dotnet_diagnostic.CA2100.severity = warning diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs index 3440b130d48c3..9a8b8b4eb6c62 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace ca1001 { @@ -8,7 +8,7 @@ public class MutableItems { // CA1002: Change 'List' in 'MutableItems.Items' to // use 'Collection', 'ReadOnlyCollection' or 'KeyedCollection'. - public List Items { get; } = new List(); + public List Items { get; } = []; public void Add(string item) { @@ -19,7 +19,7 @@ public void Add(string item) // This class satisfies the rule. public class ReadOnlyItems { - private readonly List _items = new List(); + private readonly List _items = []; public IReadOnlyCollection Items => _items.AsReadOnly(); diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1024.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1024.cs index f0bae365c94fc..402c6dbcc5c71 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1024.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1024.cs @@ -92,7 +92,7 @@ public DateTime GetScheduleTime() // Time-consuming method that is called by GetCustomerHistory. Appointment[] LoadHistoryFromDB(long customerID) { - ArrayList records = new ArrayList(); + ArrayList records = []; // Load from database. return (Appointment[])records.ToArray(); } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs index c2de821540bda..2615245d86035 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; namespace ca1031 @@ -7,14 +7,14 @@ namespace ca1031 // Creates two violations of the rule. public class GenericExceptionsCaught { - FileStream? inStream; - FileStream? outStream; + private readonly FileStream? _inStream; + private readonly FileStream? _outStream; public GenericExceptionsCaught(string inFile, string outFile) { try { - inStream = File.Open(inFile, FileMode.Open); + _inStream = File.Open(inFile, FileMode.Open); } catch (SystemException) { @@ -23,7 +23,7 @@ public GenericExceptionsCaught(string inFile, string outFile) try { - outStream = File.Open(outFile, FileMode.Open); + _outStream = File.Open(outFile, FileMode.Open); } catch { @@ -34,28 +34,28 @@ public GenericExceptionsCaught(string inFile, string outFile) public class GenericExceptionsCaughtFixed { - FileStream? inStream; - FileStream outStream; + private readonly FileStream? _inStream; + private readonly FileStream _outStream; public GenericExceptionsCaughtFixed(string inFile, string outFile) { try { - inStream = File.Open(inFile, FileMode.Open); + _inStream = File.Open(inFile, FileMode.Open); } // Fix the first violation by catching a specific exception. catch (FileNotFoundException) { Console.WriteLine($"Unable to open {inFile}."); - }; + } // For functionally equivalent code, also catch // remaining exceptions that may be thrown by File.Open try { - outStream = File.Open(outFile, FileMode.Open); + _outStream = File.Open(outFile, FileMode.Open); } // Fix the second violation by rethrowing the generic diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1032.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1032.cs index 37dae1e859621..8b5ca1a42d892 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1032.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1032.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.Serialization; namespace ca1032 { diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs index 939daf9bf15ff..43edcdaafdeee 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; // @@ -99,11 +99,11 @@ public override int GetHashCode() } public static bool operator <(RatingInformation left, RatingInformation right) { - return (Compare(left, right) < 0); + return Compare(left, right) < 0; } public static bool operator >(RatingInformation left, RatingInformation right) { - return (Compare(left, right) > 0); + return Compare(left, right) > 0; } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs index cab84b003229e..2e69200538816 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1045 { @@ -26,11 +26,12 @@ public class BadRefAndOut public static bool ReplyInformation(TypeOfFeedback input, out string reply, ref Actions action) { - bool returnReply = false; - string replyText = "Your feedback has been forwarded " + - "to the product manager."; + string replyText = """ + Your feedback has been forwarded to the product manager. + """; - reply = String.Empty; + reply = string.Empty; + bool returnReply; switch (input) { case TypeOfFeedback.Complaint: @@ -57,66 +58,33 @@ public static bool ReplyInformation(TypeOfFeedback input, // Redesigned version does not use out or ref parameters; // instead, it returns this container type. - public class ReplyData + public record class ReplyData(string Reply, Actions Action, bool ReturnReply = false) { - string reply; - Actions action; - bool returnReply; - - // Constructors. - public ReplyData() - { - this.reply = String.Empty; - this.action = Actions.Discard; - this.returnReply = false; - } - - public ReplyData(Actions action, string reply, bool returnReply) - { - this.reply = reply; - this.action = action; - this.returnReply = returnReply; - } - - // Properties. - public string Reply { get { return reply; } } - public Actions Action { get { return action; } } - public override string ToString() { - return String.Format("Reply: {0} Action: {1} return? {2}", - reply, action.ToString(), returnReply.ToString()); + return string.Format("Reply: {0} Action: {1} return? {2}", + Reply, Action.ToString(), ReturnReply.ToString()); } } public class RedesignedRefAndOut { - public static ReplyData ReplyInformation(TypeOfFeedback input) + public static ReplyData? ReplyInformation(TypeOfFeedback input) { - ReplyData answer; string replyText = "Your feedback has been forwarded " + "to the product manager."; - - switch (input) + ReplyData? answer = input switch { - case TypeOfFeedback.Complaint: - case TypeOfFeedback.Praise: - answer = new ReplyData( - Actions.ForwardToManagement, - "Thank you. " + replyText, - true); - break; - case TypeOfFeedback.Suggestion: - answer = new ReplyData( - Actions.ForwardToDeveloper, - replyText, - true); - break; - case TypeOfFeedback.Incomprehensible: - default: - answer = new ReplyData(); - break; - } + TypeOfFeedback.Complaint or TypeOfFeedback.Praise => new ReplyData( + "Thank you. " + replyText, + Actions.ForwardToManagement, + true), + TypeOfFeedback.Suggestion => new ReplyData( + replyText, + Actions.ForwardToDeveloper, + true), + _ => null, + }; return answer; } } @@ -133,13 +101,13 @@ static void UseTheComplicatedClass() string[] reply = new string[5]; // You must initialize a ref parameter. - Actions[] action = {Actions.Unknown,Actions.Unknown, + Actions[] action = [Actions.Unknown,Actions.Unknown, Actions.Unknown,Actions.Unknown, - Actions.Unknown,Actions.Unknown}; + Actions.Unknown,Actions.Unknown]; bool[] disposition = new bool[5]; int i = 0; - foreach (TypeOfFeedback t in Enum.GetValues(typeof(TypeOfFeedback))) + foreach (TypeOfFeedback t in Enum.GetValues()) { // The call to the library. disposition[i] = BadRefAndOut.ReplyInformation( @@ -153,7 +121,7 @@ static void UseTheSimplifiedClass() { ReplyData[] answer = new ReplyData[5]; int i = 0; - foreach (TypeOfFeedback t in Enum.GetValues(typeof(TypeOfFeedback))) + foreach (TypeOfFeedback t in Enum.GetValues()) { // The call to the library. answer[i] = RedesignedRefAndOut.ReplyInformation(t); diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs index 3848b3cfafab2..ed6831938086c 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1046 { @@ -24,8 +24,8 @@ public class ReferenceTypeEquality { public static void Main1046() { - MyReferenceType a = new MyReferenceType(2, 2); - MyReferenceType b = new MyReferenceType(2, 2); + MyReferenceType a = new(2, 2); + MyReferenceType b = new(2, 2); MyReferenceType c = a; Console.WriteLine($"a = new {a} and b = new {b} are equal? {(a.Equals(b) ? "Yes" : "No")}"); diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1050.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1050.cs index 75b0d245895f1..29f2cc10df858 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1050.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1050.cs @@ -30,10 +30,10 @@ public class MainHolder { public static void Main1050() { - Test t1 = new Test(); + Test t1 = new(); Console.WriteLine(t1.ToString()); - ca1050.Test t2 = new ca1050.Test(); + ca1050.Test t2 = new(); Console.WriteLine(t2.ToString()); } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1051.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1051.cs index 9b84c83d488a2..3c8660379d2f8 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1051.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1051.cs @@ -9,13 +9,7 @@ public class BadPublicInstanceFields public class GoodPublicInstanceFields { - private int instanceData = 32; - - public int InstanceData - { - get { return instanceData; } - set { instanceData = value; } - } + public int InstanceData { get; set; } = 32; } // } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1060.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1060.cs index d4018a7e60e34..a047e6902733f 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1060.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1060.cs @@ -1,7 +1,6 @@ using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; -using System.Security.Permissions; namespace ca1060 { diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1061.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1061.cs index bcb34247e1271..40a328d887976 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1061.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1061.cs @@ -34,7 +34,7 @@ class Test { static void Main1061() { - DerivedType derived = new DerivedType(); + DerivedType derived = new(); // Calls DerivedType.MethodOne. derived.MethodOne("string1", "string2"); diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1420.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1420.cs index 0bca32fcf8b96..042e98a81bae2 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1420.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1420.cs @@ -1,5 +1,5 @@ +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; [assembly: DisableRuntimeMarshalling] @@ -7,5 +7,5 @@ class C { // Violates rule CA1420. [DllImport("NativeLibrary", SetLastError = true)] - public static extern void MyMethod (); + public static extern void MyMethod(); } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1806.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1806.cs index 9607f78cc07a2..021414888b23e 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1806.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1806.cs @@ -3,23 +3,15 @@ // public class Book { - private readonly string? _Title; - public Book(string title) { - if (title != null) - { - // Violates this rule - title.Trim(); - } + // Violates this rule. + title?.Trim(); - _Title = title; + Title = title; } - public string? Title - { - get { return _Title; } - } + public string? Title { get; } } // } @@ -29,22 +21,13 @@ namespace ca1806_2 // public class Book { - private readonly string? _Title; - public Book(string title) { - if (title != null) - { - title = title.Trim(); - } - - _Title = title; + // Fixes the violation. + Title = title?.Trim(); } - public string? Title - { - get { return _Title; } - } + public string? Title { get; } } // } @@ -54,13 +37,11 @@ namespace ca1806_3 // public class Book { - public Book() - { - } + public Book() { } public static Book CreateBook() { - // Violates this rule + // Violates this rule. new Book(); return new Book(); } @@ -73,12 +54,11 @@ namespace ca1806_4 // public class Book { - public Book() - { - } + public Book() { } public static Book CreateBook() { + // Fixes the violation. return new Book(); } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1810.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1810.cs index 3098a86426924..947f357db1855 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1810.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1810.cs @@ -14,7 +14,7 @@ static StaticConstructor() { someInteger = 3; ResourceManager stringManager = - new ResourceManager("strings", Assembly.GetExecutingAssembly()); + new("strings", Assembly.GetExecutingAssembly()); resourceString = stringManager.GetString("string"); } @@ -32,7 +32,7 @@ public class NoStaticConstructor static string? InitializeResourceString() { ResourceManager stringManager = - new ResourceManager("strings", Assembly.GetExecutingAssembly()); + new("strings", Assembly.GetExecutingAssembly()); return stringManager.GetString("string"); } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1813.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1813.cs index 9fcba5ce71f59..5975b8f9e544d 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1813.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1813.cs @@ -7,19 +7,12 @@ namespace ca1813 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public sealed class DeveloperAttribute : Attribute { - private string nameValue; public DeveloperAttribute(string name) { - nameValue = name; + Name = name; } - public string Name - { - get - { - return nameValue; - } - } + public string Name { get; } } // } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1816.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1816.cs index 8796bc6d5b653..c60d5af04f7e3 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1816.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1816.cs @@ -1,12 +1,12 @@ using System; -using System.Data.SqlClient; +using System.IO; namespace ca1816 { // - public class DatabaseConnector : IDisposable + public class MyStreamClass : IDisposable { - private SqlConnection? _Connection = new SqlConnection(); + private MemoryStream? _stream = new(); public void Dispose() { @@ -18,11 +18,8 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_Connection != null) - { - _Connection.Dispose(); - _Connection = null; - } + _stream?.Dispose(); + _stream = null; } } } @@ -32,9 +29,9 @@ protected virtual void Dispose(bool disposing) namespace ca1816_2 { // - public class DatabaseConnector : IDisposable + public class MyStreamClass : IDisposable { - private SqlConnection? _Connection = new SqlConnection(); + private MemoryStream? _stream = new(); public void Dispose() { @@ -46,11 +43,8 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_Connection != null) - { - _Connection.Dispose(); - _Connection = null; - } + _stream?.Dispose(); + _stream = null; } } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1819.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1819.cs index fa69ef07f939b..6163cec8f9c16 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1819.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1819.cs @@ -5,17 +5,12 @@ namespace ca1819 // public class Book { - private string[] _Pages; - public Book(string[] pages) { - _Pages = pages; + Pages = pages; } - public string[] Pages - { - get { return _Pages; } - } + public string[] Pages { get; } } // } @@ -47,16 +42,12 @@ namespace ca1819_3 // public class Book { - private ReadOnlyCollection _Pages; public Book(string[] pages) { - _Pages = new ReadOnlyCollection(pages); + Pages = new ReadOnlyCollection(pages); } - public ReadOnlyCollection Pages - { - get { return _Pages; } - } + public ReadOnlyCollection Pages { get; } } // } @@ -66,18 +57,12 @@ namespace ca1819_4 // public class Book { - private string[] _Pages; - public Book(string[] pages) { - _Pages = pages; + Pages = pages; } - public string[] Pages - { - get { return _Pages; } - set { _Pages = value; } - } + public string[] Pages { get; set; } } // } @@ -87,17 +72,12 @@ namespace ca1819_5 // public class Book { - private Collection _Pages; - public Book(string[] pages) { - _Pages = new Collection(pages); + Pages = new Collection(pages); } - public Collection Pages - { - get { return _Pages; } - } + public Collection Pages { get; } } // } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2002.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2002.cs index ac06488f4ce78..4a71e590052ba 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2002.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2002.cs @@ -14,7 +14,7 @@ void LockOnWeakId1() void LockOnWeakId2() { - MemoryStream stream = new MemoryStream(); + MemoryStream stream = new(); lock (stream) { } } @@ -30,7 +30,7 @@ void LockOnWeakId4() } void LockOnWeakId5() { - OutOfMemoryException outOfMemory = new OutOfMemoryException(); + OutOfMemoryException outOfMemory = new(); lock (outOfMemory) { } } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2022.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2022.cs index 7efa307d45ea8..9419abe1d4265 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2022.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2022.cs @@ -1,5 +1,4 @@ using System.IO; -using System.Threading; namespace ca2022; diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2100.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2100.cs index 89e1d35ab5fa9..99fb5c2dbfcdc 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2100.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2100.cs @@ -1,16 +1,17 @@ -using System.Data; -using System.Data.SqlClient; +using System.Data.OleDb; +using System.Runtime.Versioning; namespace ca2100 { // - public class SqlQueries + [SupportedOSPlatform("Windows")] + public class OleDbQueries { public object UnsafeQuery( string connection, string name, string password) { - SqlConnection someConnection = new SqlConnection(connection); - SqlCommand someCommand = new SqlCommand(); + using OleDbConnection someConnection = new(connection); + using OleDbCommand someCommand = new(); someCommand.Connection = someConnection; someCommand.CommandText = "SELECT AccountNumber FROM Users " + @@ -26,14 +27,14 @@ public object UnsafeQuery( public object SaferQuery( string connection, string name, string password) { - SqlConnection someConnection = new SqlConnection(connection); - SqlCommand someCommand = new SqlCommand(); + using OleDbConnection someConnection = new(connection); + using OleDbCommand someCommand = new(); someCommand.Connection = someConnection; someCommand.Parameters.Add( - "@username", SqlDbType.NChar).Value = name; + "@username", OleDbType.Char).Value = name; someCommand.Parameters.Add( - "@password", SqlDbType.NChar).Value = password; + "@password", OleDbType.Char).Value = password; someCommand.CommandText = "SELECT AccountNumber FROM Users " + "WHERE Username=@username AND Password=@password"; @@ -44,11 +45,12 @@ public object SaferQuery( } } + [SupportedOSPlatform("Windows")] class MaliciousCode { static void Main2100(string[] args) { - SqlQueries queries = new SqlQueries(); + OleDbQueries queries = new(); queries.UnsafeQuery(args[0], "' OR 1=1 --", "[PLACEHOLDER]"); // Resultant query (which is always true): // SELECT AccountNumber FROM Users WHERE Username='' OR 1=1 diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2200.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2200.cs index 0330140d2d67f..b8edbdfe0821e 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2200.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2200.cs @@ -7,7 +7,7 @@ class TestsRethrow { static void Main2200() { - TestsRethrow testRethrow = new TestsRethrow(); + TestsRethrow testRethrow = new(); testRethrow.CatchException(); } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2213.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2213.cs index dac128725bc4a..b08362ce7baea 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2213.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2213.cs @@ -33,7 +33,7 @@ public void Dispose() public class TypeB : IDisposable { // Assume this type has some unmanaged resources. - TypeA aFieldOfADisposableType = new TypeA(); + TypeA aFieldOfADisposableType = new(); private bool disposed = false; protected virtual void Dispose(bool disposing) diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs index 0683515678163..890beff4bfb10 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca2214 { @@ -37,7 +37,7 @@ public class TestBadlyConstructedType { public static void Main2214() { - DerivedType derivedInstance = new DerivedType(); + DerivedType derivedInstance = new(); } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2227.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2227.cs index d1752afa5a0b9..71f2858835f32 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2227.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2227.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections; +using System.Collections; namespace ca2227 { @@ -25,13 +24,14 @@ class ReplaceWritableCollection { static void Main2227() { - ArrayList newCollection = new ArrayList(new string[] { "a", "new", "collection" }); + ArrayList newCollection = ["a", "new", "collection"]; - WritableCollection collection = new WritableCollection(); - - // This line of code demonstrates how the entire collection - // can be replaced by a property that's not read only. - collection.SomeStrings = newCollection; + WritableCollection collection = new() + { + // This line of code demonstrates how the entire collection + // can be replaced by a property that's not read only. + SomeStrings = newCollection + }; // If the intent is to replace an entire collection, // implement and/or use the Clear() and AddRange() methods instead. diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2231.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2231.cs index 545772f5107de..8ddac37ef0245 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2231.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2231.cs @@ -30,7 +30,7 @@ public override bool Equals(object? obj) return false; PointWithoutHash p = (PointWithoutHash)obj; - return ((this.x == p.x) && (this.y == p.y)); + return (this.x == p.x) && (this.y == p.y); } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2234.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2234.cs index 5a7b5f239b3bb..65abc5d8337f5 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2234.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2234.cs @@ -11,7 +11,7 @@ internal void AddToHistory(Uri uriType) { } public class Browser { - History uriHistory = new History(); + History uriHistory = new(); public void ErrorProne() { @@ -22,7 +22,7 @@ public void SaferWay() { try { - Uri newUri = new Uri("http://www.adventure-works.com"); + Uri newUri = new("http://www.adventure-works.com"); uriHistory.AddToHistory(newUri); } catch (UriFormatException) { } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2235.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2235.cs index 485b3bf5993ee..8f7fc537ed202 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2235.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2235.cs @@ -3,37 +3,21 @@ namespace ca2235 { // - public class Mouse + public class Mouse(int numberOfButtons, string scanType) { - int buttons; - string scanTypeValue; - - public int NumberOfButtons - { - get { return buttons; } - } - - public string ScanType - { - get { return scanTypeValue; } - } - - public Mouse(int numberOfButtons, string scanType) - { - buttons = numberOfButtons; - scanTypeValue = scanType; - } + public int NumberOfButtons { get; } = numberOfButtons; + public string ScanType { get; } = scanType; } [Serializable] public class InputDevices1 { // Violates MarkAllNonSerializableFields. - Mouse opticalMouse; + readonly Mouse _opticalMouse; public InputDevices1() { - opticalMouse = new Mouse(5, "optical"); + _opticalMouse = new Mouse(5, "optical"); } } @@ -42,11 +26,11 @@ public class InputDevices2 { // Satisfies MarkAllNonSerializableFields. [NonSerialized] - Mouse opticalMouse; + readonly Mouse _opticalMouse; public InputDevices2() { - opticalMouse = new Mouse(5, "optical"); + _opticalMouse = new Mouse(5, "optical"); } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/.editorconfig b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/.editorconfig index 7f80d2f28f742..8766482eea080 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/.editorconfig +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/.editorconfig @@ -2,3 +2,4 @@ dotnet_diagnostic.CA1420.severity = suggestion dotnet_diagnostic.CA1422.severity = suggestion dotnet_diagnostic.CA2200.severity = suggestion +dotnet_diagnostic.CA2100.severity = warning diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1816-call-gc-suppressfinalize-correctly_1.vb b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1816-call-gc-suppressfinalize-correctly_1.vb index b204b93e14c7b..8704eac036439 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1816-call-gc-suppressfinalize-correctly_1.vb +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1816-call-gc-suppressfinalize-correctly_1.vb @@ -1,25 +1,24 @@ -Imports System -Imports System.Data.SqlClient +Imports System.IO Namespace ca1816 ' - Public Class DatabaseConnector + Public Class MyStreamClass Implements IDisposable - Private _Connection As New SqlConnection + Private _stream As New MemoryStream Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) - ' Violates rules + ' Violates rule. GC.SuppressFinalize(True) End Sub Protected Overridable Sub Dispose(ByVal disposing As Boolean) If disposing Then - If _Connection IsNot Nothing Then - _Connection.Dispose() - _Connection = Nothing + If _stream IsNot Nothing Then + _stream.Dispose() + _stream = Nothing End If End If End Sub @@ -31,10 +30,10 @@ End Namespace Namespace ca1816_2 ' - Public Class DatabaseConnector + Public Class MyStreamClass Implements IDisposable - Private _Connection As New SqlConnection + Private _stream As New MemoryStream Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) @@ -43,9 +42,9 @@ Namespace ca1816_2 Protected Overridable Sub Dispose(ByVal disposing As Boolean) If disposing Then - If _Connection IsNot Nothing Then - _Connection.Dispose() - _Connection = Nothing + If _stream IsNot Nothing Then + _stream.Dispose() + _stream = Nothing End If End If End Sub diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2100-review-sql-queries-for-security-vulnerabilities_1.vb b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2100-review-sql-queries-for-security-vulnerabilities_1.vb index cf153ce265a3d..ae9b24a4002f2 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2100-review-sql-queries-for-security-vulnerabilities_1.vb +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2100-review-sql-queries-for-security-vulnerabilities_1.vb @@ -1,20 +1,21 @@ -Imports System -Imports System.Data -Imports System.Data.SqlClient +Imports System.Data +Imports System.Data.OleDb +Imports System.Runtime.Versioning Namespace ca2100 Public Class SqlQueries + Function UnsafeQuery(connection As String, name As String, password As String) As Object - Dim someConnection As New SqlConnection(connection) - Dim someCommand As New SqlCommand() - someCommand.Connection = someConnection - - someCommand.CommandText = "SELECT AccountNumber FROM Users " & - "WHERE Username='" & name & "' AND Password='" & password & "'" + Dim someConnection As New OleDbConnection(connection) + Dim someCommand As New OleDbCommand With { + .Connection = someConnection, + .CommandText = "SELECT AccountNumber FROM Users " & + "WHERE Username='" & name & "' AND Password='" & password & "'" + } someConnection.Open() Dim accountNumber As Object = someCommand.ExecuteScalar() @@ -23,17 +24,19 @@ Namespace ca2100 End Function + Function SaferQuery(connection As String, name As String, password As String) As Object - Dim someConnection As New SqlConnection(connection) - Dim someCommand As New SqlCommand() - someCommand.Connection = someConnection + Dim someConnection As New OleDbConnection(connection) + Dim someCommand As New OleDbCommand With { + .Connection = someConnection + } - someCommand.Parameters.Add( - "@username", SqlDbType.NChar).Value = name - someCommand.Parameters.Add( - "@password", SqlDbType.NChar).Value = password + someCommand.Parameters.AddWithValue( + "@username", OleDbType.Char).Value = name + someCommand.Parameters.AddWithValue( + "@password", OleDbType.Char).Value = password someCommand.CommandText = "SELECT AccountNumber FROM Users " & "WHERE Username=@username AND Password=@password" @@ -48,6 +51,7 @@ Namespace ca2100 Class MaliciousCode + Shared Sub Main2100(args As String()) Dim queries As New SqlQueries()