diff --git a/.editorconfig b/.editorconfig index 251d904316c..da4aa372085 100644 --- a/.editorconfig +++ b/.editorconfig @@ -264,7 +264,7 @@ dotnet_diagnostic.IDE0057.severity = suggestion dotnet_diagnostic.IDE0058.severity = silent # IDE0059: Unnecessary assignment of a value -dotnet_diagnostic.IDE0059.severity = suggestion # TODO: warning +dotnet_diagnostic.IDE0059.severity = warning # IDE0060: Remove unused parameter dotnet_diagnostic.IDE0060.severity = silent @@ -708,7 +708,7 @@ dotnet_diagnostic.CA1819.severity = none dotnet_diagnostic.CA1820.severity = none # CA1821: Remove empty Finalizers -dotnet_diagnostic.CA1821.severity = none # TODO: warning +dotnet_diagnostic.CA1821.severity = warning # CA1822: Mark members as static dotnet_diagnostic.CA1822.severity = warning @@ -1523,8 +1523,8 @@ dotnet_diagnostic.SA1204.severity = none # SA1205: Partial elements should declare an access modifier dotnet_diagnostic.SA1205.severity = warning -# SA1206: Keyword ordering - TODO Re-enable as warning after https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3527 -dotnet_diagnostic.SA1206.severity = suggestion +# SA1206: Keyword ordering +dotnet_diagnostic.SA1206.severity = warning # SA1207: Protected should come before internal dotnet_diagnostic.SA1207.severity = none diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/VbFileCleanupTestBaseTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/VbFileCleanupTestBaseTests.vb index 1e69b347326..ca3a32a4b36 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/VbFileCleanupTestBaseTests.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/VbFileCleanupTestBaseTests.vb @@ -14,9 +14,9 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub CreateTempDirectoryTest() Dim tempDirectory As String = CreateTempDirectory() tempDirectory.Should.StartWith(Path.GetTempPath) - tempDirectory = CreateTempDirectory() + CreateTempDirectory() _testDirectories.Count.Should.Be(1) - tempDirectory = CreateTempDirectory(lineNumber:=1) + CreateTempDirectory(lineNumber:=1) _testDirectories.Count.Should.Be(2) End Sub diff --git a/src/System.Drawing.Common/tests/System/Drawing/Printing/PrinterSettingsTests.cs b/src/System.Drawing.Common/tests/System/Drawing/Printing/PrinterSettingsTests.cs index 29660da2f69..e93960cfaf1 100644 --- a/src/System.Drawing.Common/tests/System/Drawing/Printing/PrinterSettingsTests.cs +++ b/src/System.Drawing.Common/tests/System/Drawing/Printing/PrinterSettingsTests.cs @@ -43,14 +43,14 @@ public void Ctor_Default_Success() public void CanDuplex_ReturnsExpected() { PrinterSettings printerSettings = new(); - bool canDuplex = printerSettings.CanDuplex; + _ = printerSettings.CanDuplex; } [Fact] public void Copies_Default_ReturnsExpected() { PrinterSettings printerSettings = new(); - int copies = printerSettings.Copies; + _ = printerSettings.Copies; } [Theory] @@ -79,7 +79,7 @@ public void Copies_SetValue_ThrowsArgumentException(short copies) public void Collate_Default_ReturnsExpected() { PrinterSettings printerSettings = new(); - bool collate = printerSettings.Collate; + _ = printerSettings.Collate; } [Fact] @@ -380,7 +380,7 @@ public static IEnumerable IsDirectPrintingSupported_ImageFormatSupport public void IsDirectPrintingSupported_ImageFormatSupported_ReturnsExpected(ImageFormat imageFormat) { PrinterSettings printerSettings = new(); - bool supported = printerSettings.IsDirectPrintingSupported(imageFormat); + _ = printerSettings.IsDirectPrintingSupported(imageFormat); } public static IEnumerable IsDirectPrintingSupported_ImageFormatNotSupported_TestData() @@ -508,10 +508,8 @@ public void CreateMeasurementGraphics_Null_ThrowsNullReferenceException() public void GetHdevmode_ReturnsExpected() { PrinterSettings printerSettings = new(); - IntPtr handle = IntPtr.Zero; - - handle = printerSettings.GetHdevmode(); - Assert.NotEqual(IntPtr.Zero, handle); + nint handle = printerSettings.GetHdevmode(); + Assert.NotEqual(0, handle); } [Fact] @@ -519,10 +517,8 @@ public void GetHdevmode_PageSettings_ReturnsExpected() { PrinterSettings printerSettings = new(); PageSettings pageSettings = new(); - IntPtr handle = IntPtr.Zero; - - handle = printerSettings.GetHdevmode(pageSettings); - Assert.NotEqual(IntPtr.Zero, handle); + nint handle = printerSettings.GetHdevmode(pageSettings); + Assert.NotEqual(0, handle); } [Fact] @@ -536,10 +532,8 @@ public void GetHdevmode_Null_ThrowsNullReferenceException() public void GetHdevnames_ReturnsExpected() { PrinterSettings printerSettings = new(); - IntPtr handle = IntPtr.Zero; - - handle = printerSettings.GetHdevnames(); - Assert.NotEqual(IntPtr.Zero, handle); + nint handle = printerSettings.GetHdevnames(); + Assert.NotEqual(0, handle); } [ConditionalFact(typeof(PrinterSettingsTests), nameof(CanTestSetHdevmode_IntPtr_Success))] diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs index df547abaab7..c1ddee4c0bc 100644 --- a/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs +++ b/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs @@ -83,7 +83,7 @@ private static void CheckForEmptyBitmap(Bitmap bitmap) private static void CheckForNonEmptyBitmap(Bitmap bitmap) { - if (IsEmptyBitmap(bitmap, out int x, out int y)) + if (IsEmptyBitmap(bitmap, out int _, out int _)) Assert.True(false); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs index 0f41c451a1d..8e7104e8b29 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs @@ -293,49 +293,49 @@ public virtual CodeStatementCollection SerializeMemberAbsolute(IDesignerSerializ [Obsolete("This method has been deprecated. Use SerializeToExpression or GetExpression instead. https://go.microsoft.com/fwlink/?linkid=14202")] protected CodeExpression? SerializeToReferenceExpression(IDesignerSerializationManager manager, object value) { - CodeExpression? expression = null; - // First - try GetExpression - expression = GetExpression(manager, value); + if (GetExpression(manager, value) is { } expression) + { + return expression; + } + + if (value is not IComponent) + { + return null; + } + // Next, we check for a named IComponent, and return a reference to it. - if (expression is null && value is IComponent) + string? name = manager.GetName(value); + bool referenceName = false; + if (name is null) { - string? name = manager.GetName(value); - bool referenceName = false; - if (name is null) + IReferenceService? referenceService = manager.GetService(); + if (referenceService is not null) { - IReferenceService? referenceService = manager.GetService(); - if (referenceService is not null) - { - name = referenceService.GetName(value); - referenceName = name is not null; - } + name = referenceService.GetName(value); + referenceName = name is not null; } + } - if (name is not null) - { - // Check to see if this is a reference to the root component. If it is, then use "this". - if (manager.TryGetContext(out RootContext? root) && root.Value == value) - { - expression = root.Expression; - } - else - { - int dotIndex = name.IndexOf('.'); - if (referenceName && dotIndex != -1) - { - // if it's a reference name with a dot, we've actually got a property here... - expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(s_thisRef, name[..dotIndex]), name[(dotIndex + 1)..]); - } - else - { - expression = new CodeFieldReferenceExpression(s_thisRef, name); - } - } - } + if (name is null) + { + return null; + } + + // Check to see if this is a reference to the root component. If it is, then use "this". + if (manager.TryGetContext(out RootContext? root) && root.Value == value) + { + return root.Expression; } - return expression; + // If it's a reference name with a dot, we've actually got a property. + + int dotIndex = name.IndexOf('.'); + return referenceName && dotIndex != -1 + ? new CodePropertyReferenceExpression( + new CodeFieldReferenceExpression(s_thisRef, name[..dotIndex]), + name[(dotIndex + 1)..]) + : new CodeFieldReferenceExpression(s_thisRef, name); } private static void ResetBrowsableProperties(object? instance) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 845cafda7c9..43ccb471320 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -485,7 +485,7 @@ public IDisposable CreateSession() // Check for a default serialization provider if (_defaultProviderTable is null || !_defaultProviderTable.Contains(serializerType)) { - Type? defaultSerializerType = null; + Type? defaultSerializerType; DefaultSerializationProviderAttribute? attribute = (DefaultSerializationProviderAttribute?)TypeDescriptor.GetAttributes(serializerType)[typeof(DefaultSerializationProviderAttribute)]; if (attribute is not null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs index 7f249928686..958e36ed35d 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs @@ -30,13 +30,13 @@ public override object Serialize(IDesignerSerializationManager manager, object? return null!; } - bool needCast = false; + bool needCast; Enum[] values; TypeConverter? converter = TypeDescriptor.GetConverter(enumValue); if (converter is not null && converter.CanConvertTo(typeof(Enum[]))) { values = (Enum[])converter.ConvertTo(enumValue, typeof(Enum[]))!; - needCast = (values.Length > 1); + needCast = values.Length > 1; } else { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs index baa3d009ef5..ecff01f7b51 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs @@ -214,7 +214,7 @@ public virtual object Deserialize(IDesignerSerializationManager manager, CodeTyp /// private object? DeserializeName(IDesignerSerializationManager manager, string name, CodeStatementCollection? statements) { - object? value = null; + object? value; // If the name we're looking for isn't in our dictionary, we return null. // It is up to the caller to decide if this is an error or not. diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs index 0076eb366db..43e59295904 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs @@ -62,7 +62,7 @@ protected static string CreateFilterEntry(ImageEditor e) public override object? EditValue(ITypeDescriptorContext? context, IServiceProvider provider, object? value) { - if (!provider.TryGetService(out IWindowsFormsEditorService? editorService)) + if (!provider.TryGetService(out IWindowsFormsEditorService? _)) { return value; } @@ -86,6 +86,7 @@ protected static string CreateFilterEntry(ImageEditor e) binder: null, args: null, culture: null); + if (editor is not null && editor.GetType() is Type editorClass && !myClass.Equals(editorClass) @@ -118,7 +119,6 @@ protected static string CreateFilterEntry(ImageEditor e) return value; } - /// public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext? context) => UITypeEditorEditStyle.Modal; protected virtual string GetFileDialogDescription() => SR.imageFileDescription; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ToolStripPanelSelectionGlyph.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ToolStripPanelSelectionGlyph.cs index 7f9400e9174..0225ea3e4d0 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ToolStripPanelSelectionGlyph.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ToolStripPanelSelectionGlyph.cs @@ -98,8 +98,8 @@ private void SetBitmap(string fileName) private void CollapseGlyph(Rectangle bounds) { DockStyle? dock = _relatedPanel?.Dock; - int x = 0; - int y = 0; + int x; + int y; switch (dock) { @@ -147,8 +147,8 @@ private void CollapseGlyph(Rectangle bounds) private void ExpandGlyph(Rectangle bounds) { DockStyle? dock = _relatedPanel?.Dock; - int x = 0; - int y = 0; + int x; + int y; switch (dock) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCodeDomSerializer.cs index fe799ab40d9..390a928e022 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCodeDomSerializer.cs @@ -334,45 +334,58 @@ private static Type[] ToTargetTypes(object context, Type[] runtimeTypes) /// /// Serializes a method invocation on the control being serialized. Used to serialize Suspend/ResumeLayout pairs, etc. /// - private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection? parameters, Type[] paramTypes, StatementOrdering ordering) + private void SerializeMethodInvocation( + IDesignerSerializationManager manager, + CodeStatementCollection statements, + object control, + string methodName, + CodeExpressionCollection? parameters, + Type[] paramTypes, + StatementOrdering ordering) { - string? name = manager.GetName(control); + // Not doing anything with the name, keeping the access for compat. + _ = manager.GetName(control); // Use IReflect to see if this method name exists on the control. paramTypes = ToTargetTypes(control, paramTypes); - MethodInfo? mi = TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, binder: null, paramTypes, modifiers: null); - - if (mi is not null) + if (TypeDescriptor.GetReflectionType(control).GetMethod( + methodName, + BindingFlags.Public | BindingFlags.Instance, + binder: null, + paramTypes, + modifiers: null) is null) { - CodeExpression? field = SerializeToExpression(manager, control); - CodeMethodReferenceExpression method = new(field, methodName); - CodeMethodInvokeExpression methodInvoke = new() - { - Method = method - }; + return; + } - if (parameters is not null) - { - methodInvoke.Parameters.AddRange(parameters); - } + CodeExpression? field = SerializeToExpression(manager, control); + CodeMethodReferenceExpression method = new(field, methodName); + CodeMethodInvokeExpression methodInvoke = new() + { + Method = method + }; - CodeExpressionStatement statement = new(methodInvoke); + if (parameters is not null) + { + methodInvoke.Parameters.AddRange(parameters); + } - switch (ordering) - { - case StatementOrdering.Prepend: - statement.UserData["statement-ordering"] = "begin"; - break; - case StatementOrdering.Append: - statement.UserData["statement-ordering"] = "end"; - break; - default: - Debug.Fail($"Unsupported statement ordering: {ordering}"); - break; - } + CodeExpressionStatement statement = new(methodInvoke); - statements.Add(statement); + switch (ordering) + { + case StatementOrdering.Prepend: + statement.UserData["statement-ordering"] = "begin"; + break; + case StatementOrdering.Append: + statement.UserData["statement-ordering"] = "end"; + break; + default: + Debug.Fail($"Unsupported statement ordering: {ordering}"); + break; } + + statements.Add(statement); } private void SerializePerformLayout(IDesignerSerializationManager manager, CodeStatementCollection statements, object control) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs index 91468f43523..74f02794c36 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs @@ -1665,7 +1665,7 @@ protected override void PreFilterProperties(IDictionary properties) } /// - /// Hooks the children of the given control. We need to do this for child controls that are not in design + /// Unhooks the children of the given control. We need to do this for child controls that are not in design /// mode, which is the case for composite controls. /// protected void UnhookChildControls(Control firstChild) @@ -1674,11 +1674,9 @@ protected void UnhookChildControls(Control firstChild) foreach (Control child in firstChild.Controls) { - IWindowTarget? oldTarget = null; if (child is not null) { - // No, no designer means we must replace the window target in this control. - oldTarget = child.WindowTarget; + IWindowTarget? oldTarget = child.WindowTarget; if (oldTarget is ChildWindowTarget target) { child.WindowTarget = target.OldWindowTarget; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewAddColumnDialog.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewAddColumnDialog.cs index 342f35091ba..acc4ae47f07 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewAddColumnDialog.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewAddColumnDialog.cs @@ -52,8 +52,7 @@ public DataGridViewAddColumnDialog(DataGridViewColumnCollection dataGridViewColu _liveDataGridView = liveDataGridView; // PERF: set the Dialog Font before InitializeComponent. - // - Font uiFont = Control.DefaultFont; + Font uiFont = DefaultFont; if (_liveDataGridView.Site.TryGetService(out IUIService? uiService)) { uiFont = (Font)uiService.Styles["DialogFont"]!; @@ -639,14 +638,14 @@ private void nameTextBox_Validating(object? sender, CancelEventArgs e) nameCreationService = _liveDataGridView.Site.GetService(); } - string errorString = string.Empty; - if (!ValidName(_nameTextBox.Text, - _dataGridViewColumns, - container, - nameCreationService, - _liveDataGridView.Columns, - !_persistChangesToDesigner, - out errorString)) + if (!ValidName( + _nameTextBox.Text, + _dataGridViewColumns, + container, + nameCreationService, + _liveDataGridView.Columns, + !_persistChangesToDesigner, + out string errorString)) { IUIService? uiService = _liveDataGridView.Site?.GetService(); DataGridViewDesigner.ShowErrorDialog(uiService, errorString, _liveDataGridView); @@ -717,7 +716,6 @@ private void PopulateDataColumns() } catch (ArgumentException) { - currencyManager = null; } PropertyDescriptorCollection? propertyDescriptorCollection = currencyManager?.GetItemProperties(); @@ -742,14 +740,9 @@ private void PopulateDataColumns() } } - if (selectedIndex != -1 && selectedIndex < _dataColumns.Items.Count) - { - _dataColumns.SelectedIndex = selectedIndex; - } - else - { - _dataColumns.SelectedIndex = _dataColumns.Items.Count > 0 ? 0 : -1; - } + _dataColumns.SelectedIndex = selectedIndex != -1 && selectedIndex < _dataColumns.Items.Count + ? selectedIndex + : _dataColumns.Items.Count > 0 ? 0 : -1; } private void addButton_Click(object? sender, EventArgs e) @@ -778,14 +771,14 @@ protected override bool ProcessDialogKey(Keys keyData) IContainer? container = host?.Container; INameCreationService? nameCreationService = _liveDataGridView.Site?.GetService(); - string errorString = string.Empty; - if (ValidName(_nameTextBox.Text, - _dataGridViewColumns, - container, - nameCreationService, - _liveDataGridView.Columns, - !_persistChangesToDesigner, - out errorString)) + if (ValidName( + _nameTextBox.Text, + _dataGridViewColumns, + container, + nameCreationService, + _liveDataGridView.Columns, + !_persistChangesToDesigner, + out string errorString)) { AddColumn(); Close(); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewColumnCollectionDialog.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewColumnCollectionDialog.cs index ce4f5ac01a5..1c92d8d4eb6 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewColumnCollectionDialog.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DataGridViewColumnCollectionDialog.cs @@ -361,8 +361,6 @@ private static void CopyDefaultCellStyle(DataGridViewColumn srcColumn, DataGridV { throw; } - - defaultSrcColumn = null; } // 2.b Go thru the public properties in the DataGridViewCellStyle and copy only the property @@ -1269,7 +1267,7 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? at { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(DataGridViewColumn); - PropertyDescriptor[]? propArray = null; + PropertyDescriptor[]? propArray; if (DataGridViewColumnDesigner is not null) { // PropertyDescriptorCollection does not let us change properties. @@ -1302,17 +1300,8 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? at return new PropertyDescriptorCollection(propArray); } - object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) - { - if (pd is ColumnTypePropertyDescriptor) - { - return this; - } - else - { - return DataGridViewColumn; - } - } + object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) => + pd is ColumnTypePropertyDescriptor ? this : DataGridViewColumn; ISite? IComponent.Site { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignBindingPicker.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignBindingPicker.cs index fd7af6b19ee..2020d974386 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignBindingPicker.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignBindingPicker.cs @@ -440,7 +440,6 @@ public DesignBindingPicker() _windowsFormsEditorService = null; _dataSourceProviderService = null; _designerHost = null; - context = null; // Return final selection to caller return finalSelectedItem; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs index 139dcd9b63b..aed8c39c349 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs @@ -249,12 +249,16 @@ internal virtual bool CanDropComponents(DragEventArgs de) { // If there is no tray we bail. if (_componentTray is null) + { return true; + } // Figure out if any of the components in the drag-drop are children // of our own tray. If so, we should prevent this drag-drop from proceeding. - // - OleDragDropHandler ddh = GetOleDragHandler(); + + // Keeping GetOleDragHandler() for compat. + _ = GetOleDragHandler(); + object[] dragComps = OleDragDropHandler.GetDraggingObjects(de); if (dragComps is not null) @@ -275,12 +279,7 @@ internal virtual bool CanDropComponents(DragEventArgs de) } // ToolStripItems cannot be dropped on any ParentControlDesigners since they have custom DataObject Format. - if (de.Data is ToolStripItemDataObject) - { - return false; - } - - return true; + return de.Data is not ToolStripItemDataObject; } private AxToolboxItem CreateAxToolboxItem(IDataObject dataObject) @@ -877,69 +876,55 @@ private void OnUndoing(object source, EventArgs e) /// private void OnComponentAdded(object source, ComponentEventArgs ce) { - IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); - if (host is not null) + if (!TryGetService(out IDesignerHost host)) { - IComponent component = ce.Component; + return; + } - bool addControl = true; + IComponent component = ce.Component; - // This is the mirror to logic in ParentControlDesigner. The component should be - // added somewhere, and this logic decides where. + // This is the mirror to logic in ParentControlDesigner. The component should be + // added somewhere, and this logic decides where. - // LETS SEE IF WE ARE TOOLSTRIP in which case we want to get added - // to the componentTray even though this is a control.. - // We should think of implementing an interface so that we can have many more - // controls behaving like this. + // If the component is a toolstrip or a top level form, we should add to the tray. - if (host.GetDesigner(component) is not ToolStripDesigner td) - { - ControlDesigner cd = host.GetDesigner(component) as ControlDesigner; - if (cd is not null) - { - if (cd.Control is not Form form || !form.TopLevel) - { - addControl = false; - } - } - } + IDesigner designer = host.GetDesigner(component); + bool addControl = designer is ToolStripDesigner + || designer is not ControlDesigner cd + || (cd.Control is Form form && form.TopLevel); - if (addControl && - TypeDescriptor.GetAttributes(component).Contains(DesignTimeVisibleAttribute.Yes)) - { - if (_componentTray is null) - { - ISplitWindowService sws = (ISplitWindowService)GetService(typeof(ISplitWindowService)); - if (sws is not null) - { - _componentTray = new ComponentTray(this, Component.Site); - sws.AddSplitWindow(_componentTray); + if (!addControl || !TypeDescriptor.GetAttributes(component).Contains(DesignTimeVisibleAttribute.Yes)) + { + return; + } - _componentTray.Height = _trayHeight; - _componentTray.ShowLargeIcons = _trayLargeIcon; - _componentTray.AutoArrange = _trayAutoArrange; + if (_componentTray is null && TryGetService(out ISplitWindowService sws)) + { + _componentTray = new ComponentTray(this, Component.Site); + sws.AddSplitWindow(_componentTray); - host.AddService(_componentTray); - } - } + _componentTray.Height = _trayHeight; + _componentTray.ShowLargeIcons = _trayLargeIcon; + _componentTray.AutoArrange = _trayAutoArrange; - if (_componentTray is not null) - { - // Suspend the layout of the tray through the loading - // process. This way, we won't continuously try to layout - // components in auto arrange mode. We will instead let - // the controls restore themselves to their persisted state - // and then let auto-arrange kick in once. - // - if (host is not null && host.Loading && !_trayLayoutSuspended) - { - _trayLayoutSuspended = true; - _componentTray.SuspendLayout(); - } + host.AddService(_componentTray); + } - _componentTray.AddComponent(component); - } + if (_componentTray is not null) + { + // Suspend the layout of the tray through the loading + // process. This way, we won't continuously try to layout + // components in auto arrange mode. We will instead let + // the controls restore themselves to their persisted state + // and then let auto-arrange kick in once. + + if (host is not null && host.Loading && !_trayLayoutSuspended) + { + _trayLayoutSuspended = true; + _componentTray.SuspendLayout(); } + + _componentTray.AddComponent(component); } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs index 029d5e5bc94..b550a87ebcd 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs @@ -29,7 +29,7 @@ public class ImageListImageEditor : ImageEditor } ArrayList images = []; - if (!provider.TryGetService(out IWindowsFormsEditorService? editorService)) + if (!provider.TryGetService(out IWindowsFormsEditorService? _)) { return images; } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs index 188d78f9b40..1e168abf271 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs @@ -1481,7 +1481,8 @@ protected override void OnDragEnter(DragEventArgs de) } else { - OleDragDropHandler ddh = GetOleDragHandler(); + // Keep GetOleDragHandler() for compat. + _ = GetOleDragHandler(); dragComps = OleDragDropHandler.GetDraggingObjects(de); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/PictureBoxDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/PictureBoxDesigner.cs index 167528a1723..74423de9f9c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/PictureBoxDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/PictureBoxDesigner.cs @@ -85,9 +85,9 @@ public override SelectionRules SelectionRules { SelectionRules rules = base.SelectionRules; PictureBoxSizeMode sizeMode = PictureBoxSizeMode.Normal; - PropertyDescriptorCollection props = TypeDescriptor.GetProperties(Component); - PropertyDescriptor? propSizeMode = TypeDescriptor.GetProperties(Component)["SizeMode"]; - if (props.TryGetPropertyDescriptorValue( + PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(Component); + + if (properties.TryGetPropertyDescriptorValue( "SizeMode", Component, ref sizeMode)) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StyleEditorForm.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StyleEditorForm.cs index e0009ea4eca..d513b9784e0 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StyleEditorForm.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StyleEditorForm.cs @@ -818,33 +818,30 @@ private void ClearAndSetSelectionAndFocus(int index) /// private void AddItem(int index) { - string member = null; _tableLayoutPanelDesigner.InsertRowCol(_isRowCollection, index); - member = _isRowCollection - ? "Row" + _tableLayoutPanel.RowStyles.Count.ToString(CultureInfo.InvariantCulture) - : "Column" + _tableLayoutPanel.RowStyles.Count.ToString(CultureInfo.InvariantCulture); + string member = _isRowCollection + ? $"Row{_tableLayoutPanel.RowStyles.Count}" + : $"Column{_tableLayoutPanel.RowStyles.Count}"; - if (member is not null) - { - _columnsAndRowsListView.Items.Insert( - index, - new ListViewItem( - [ - member, SizeType.Absolute.ToString(), - DesignerUtils.s_minimumStyleSize.ToString(CultureInfo.InvariantCulture) - ])); - - // If we inserted at the beginning, then we have to change the Member of string of all the existing listView items, - // so we might as well just update the entire listView. - UpdateListViewMember(); - ClearAndSetSelectionAndFocus(index); - } + _columnsAndRowsListView.Items.Insert( + index, + new ListViewItem( + [ + member, SizeType.Absolute.ToString(), + DesignerUtils.s_minimumStyleSize.ToString(CultureInfo.InvariantCulture) + ])); + + // If we inserted at the beginning, then we have to change the Member of string of all the existing listView items, + // so we might as well just update the entire listView. + UpdateListViewMember(); + ClearAndSetSelectionAndFocus(index); } private void OnAddButtonClick(object sender, EventArgs e) { _isDialogDirty = true; + // Add an item to the end of the listView AddItem(_columnsAndRowsListView.Items.Count); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TabControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TabControlDesigner.cs index 88fc6433980..8da11eb7f78 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TabControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TabControlDesigner.cs @@ -388,7 +388,8 @@ private void OnControlAdded(object sender, ControlEventArgs e) { if (e.Control is not null && !e.Control.IsHandleCreated) { - IntPtr hwnd = e.Control.Handle; + // Force handle creation. + _ = e.Control.Handle; } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TableLayoutPanelDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TableLayoutPanelDesigner.cs index d945ff8023c..1ea69253c32 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TableLayoutPanelDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TableLayoutPanelDesigner.cs @@ -679,7 +679,7 @@ private void InitializeNewStyles() private static bool SubsetExists(bool[,] cells, int columns, int rows, int subsetColumns, int subsetRows) { bool exists = false; - int column = 0; + int column; int row; for (row = 0; row < rows - subsetRows + 1; row++) @@ -1946,17 +1946,10 @@ private void OnDeleteClick(object sender, EventArgs e) private void ChangeSizeType(bool isRow, SizeType newType) { - TableLayoutStyleCollection styles = null; + TableLayoutStyleCollection styles; try { - if (isRow) - { - styles = Table.RowStyles; - } - else - { - styles = Table.ColumnStyles; - } + styles = isRow ? Table.RowStyles : Table.ColumnStyles; int index = isRow ? _curRow : _curCol; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs index 4bd12aa5eff..a67faa8347e 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs @@ -782,7 +782,6 @@ private bool CheckIfItemSelected() if (dropDown is not null) { ToolStripItem ownerItem = dropDown.OwnerItem; - ToolStripMenuItemDesigner itemDesigner = (ToolStripMenuItemDesigner)_host.GetDesigner(ownerItem); ToolStripDropDown topmost = ToolStripItemDesigner.GetFirstDropDown((ToolStripDropDownItem)(ownerItem)); ToolStripItem topMostItem = (topmost is null) ? ownerItem : topmost.OwnerItem; @@ -2385,12 +2384,12 @@ private void SelSvc_SelectionChanged(object sender, EventArgs e) } } - // REQUIRED FOR THE REFRESH OF GLYPHS BUT TRY TO BE SMART ABOUT THE REGION TO INVALIDATE.... - if (SelectionService.PrimarySelection is not ToolStripItem selectedItem) + // Required for the refresh of glyphs. + if (SelectionService.PrimarySelection is not ToolStripItem) { if (KeyboardHandlingService is not null) { - selectedItem = KeyboardHandlingService.SelectedDesignerControl as ToolStripItem; + _ = KeyboardHandlingService.SelectedDesignerControl; } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TreeNodeCollectionEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TreeNodeCollectionEditor.cs index 86e5fab5772..36eea7e4ff3 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TreeNodeCollectionEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TreeNodeCollectionEditor.cs @@ -151,7 +151,7 @@ private int NextNode private void Add(TreeNode parent) { - TreeNode newNode = null; + TreeNode newNode; string baseNodeName = SR.BaseNodeName; if (parent is null) diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs index c536ad4bed3..03141d7a67f 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs @@ -2318,7 +2318,6 @@ public void DesignerHost_GetService_IMultitargetHelperServiceWithLoader_ReturnsE [WinFormsFact] public void DesignerHost_GetServiceIMultitargetHelperServiceWithoutLoader_ReturnsNull() { - object service = new(); Mock mockServiceProvider = new(MockBehavior.Strict); SubDesignSurface surface = new(mockServiceProvider.Object); IDesignerLoaderHost2 host = surface.Host; diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs index d10dd7470d0..af9a27b9b1a 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs @@ -22,7 +22,6 @@ public void DesignerSerializationManager_Ctor_Default() Assert.Null(manager.PropertyProvider); Assert.False(manager.RecycleInstances); Assert.True(manager.ValidateRecycledTypes); - ; } public static IEnumerable Ctor_IServiceProvider_TestData() @@ -110,7 +109,7 @@ public void DesignerSerializationManager_Context_GetWithSession_ReturnsExpected( { DesignerSerializationManager manager = new(); IDesignerSerializationManager iManager = manager; - IDisposable session = manager.CreateSession(); + _ = manager.CreateSession(); ContextStack context = iManager.Context; Assert.Null(context.Current); Assert.Same(context, iManager.Context); @@ -141,7 +140,7 @@ public void DesignerSerializationManager_Context_GetNoSession_ThrowsInvalidOpera public void DesignerSerializationManager_Errors_GetWithSession_ReturnsExpected() { DesignerSerializationManager manager = new(); - IDisposable session = manager.CreateSession(); + _ = manager.CreateSession(); IList errors = manager.Errors; Assert.Empty(errors); Assert.Same(errors, manager.Errors); @@ -480,7 +479,7 @@ public void DesignerSerializationManager_CreateSession_Invoke_CallsOnSessionCrea .Protected() .Setup("OnSessionCreated", EventArgs.Empty) .Verifiable(); - IDisposable session = mockManager.Object.CreateSession(); + _ = mockManager.Object.CreateSession(); mockManager.Protected().Verify("OnSessionCreated", Times.Once(), EventArgs.Empty); } @@ -545,7 +544,7 @@ public void DesignerSerializationManager_CreateSession_Dispose_ClearsErrors() // Dispose, get another and ensure cleared. session1.Dispose(); - IDisposable session2 = manager.CreateSession(); + _ = manager.CreateSession(); IList errors2 = manager.Errors; Assert.Empty(errors2); Assert.Same(errors2, manager.Errors); @@ -565,7 +564,7 @@ public void DesignerSerializationManager_CreateSession_Dispose_ClearsContext() // Dispose, get another and ensure cleared. session1.Dispose(); - IDisposable session2 = manager.CreateSession(); + _ = manager.CreateSession(); ContextStack stack2 = iManager.Context; Assert.NotNull(stack2); Assert.Same(stack2, iManager.Context); @@ -1716,7 +1715,7 @@ public void DesignerSerializationManager_OnSessionDisposed_Invoke_ClearsErrors() SubDesignerSerializationManager manager = new(); IDesignerSerializationManager iManager = manager; - IDisposable session1 = manager.CreateSession(); + _ = manager.CreateSession(); IList errors1 = manager.Errors; Assert.Empty(errors1); Assert.Same(errors1, manager.Errors); @@ -1726,7 +1725,7 @@ public void DesignerSerializationManager_OnSessionDisposed_Invoke_ClearsErrors() // Dispose, get another and ensure cleared. manager.OnSessionDisposed(EventArgs.Empty); - IDisposable session2 = manager.CreateSession(); + _ = manager.CreateSession(); IList errors2 = manager.Errors; Assert.Empty(errors2); Assert.Same(errors2, manager.Errors); @@ -1739,14 +1738,14 @@ public void DesignerSerializationManager_OnSessionDisposed_Invoke_ClearsContext( SubDesignerSerializationManager manager = new(); IDesignerSerializationManager iManager = manager; - IDisposable session1 = manager.CreateSession(); + _ = manager.CreateSession(); ContextStack stack1 = iManager.Context; Assert.NotNull(stack1); Assert.Same(stack1, iManager.Context); // Dispose, get another and ensure cleared. manager.OnSessionDisposed(EventArgs.Empty); - IDisposable session2 = manager.CreateSession(); + _ = manager.CreateSession(); ContextStack stack2 = iManager.Context; Assert.NotNull(stack2); Assert.Same(stack2, iManager.Context); @@ -1758,7 +1757,7 @@ public void DesignerSerializationManager_OnSessionDisposed_Invoke_ClearsSerializ { SubDesignerSerializationManager manager = new(); - IDisposable session1 = manager.CreateSession(); + _ = manager.CreateSession(); object serializer1 = manager.GetSerializer(typeof(ClassWithPublicDesignerSerializer), typeof(BaseClass)); Assert.IsType(serializer1); Assert.Same(serializer1, manager.GetSerializer(typeof(ClassWithPublicDesignerSerializer), typeof(PublicDesignerSerializationProvider))); @@ -2027,32 +2026,32 @@ private class NestedClass { } - [DesignerSerializerAttribute("System.Int32", (string)null)] + [DesignerSerializer("System.Int32", (string)null)] private class ClassWithNullBaseDesignerSerializer { } - [DesignerSerializerAttribute("System.Int32", "")] + [DesignerSerializer("System.Int32", "")] private class ClassWithEmptyBaseDesignerSerializer { } - [DesignerSerializerAttribute("System.Int32", "NoSuchType")] + [DesignerSerializer("System.Int32", "NoSuchType")] private class ClassWithNoSuchBaseDesignerSerializer { } - [DesignerSerializerAttribute((string)null, typeof(int))] + [DesignerSerializer((string)null, typeof(int))] private class ClassWithNullSubDesignerSerializer { } - [DesignerSerializerAttribute("", typeof(int))] + [DesignerSerializer("", typeof(int))] private class ClassWithEmptySubDesignerSerializer { } - [DesignerSerializerAttribute("NoSuchType", typeof(int))] + [DesignerSerializer("NoSuchType", typeof(int))] private class ClassWithNoSuchSubDesignerSerializer { } @@ -2065,12 +2064,12 @@ private class SubClass : BaseClass { } - [DesignerSerializerAttribute(typeof(PublicDesignerSerializationProvider), typeof(BaseClass))] + [DesignerSerializer(typeof(PublicDesignerSerializationProvider), typeof(BaseClass))] private class ClassWithPublicDesignerSerializer { } - [DesignerSerializerAttribute(typeof(PrivateDesignerSerializationProvider), typeof(BaseClass))] + [DesignerSerializer(typeof(PrivateDesignerSerializationProvider), typeof(BaseClass))] private class ClassWithPrivateDesignerSerializer { } diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/BitmapEditorTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/BitmapEditorTests.cs index d88eb65f80c..af90b171346 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/BitmapEditorTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/BitmapEditorTests.cs @@ -19,7 +19,6 @@ public void BitmapEditor_Ctor_Default() [Fact] public void BitmapEditor_BitmapExtensions_Get_ReturnsExpected() { - SubBitmapEditor editor = new(); List extensions = SubBitmapEditor.BitmapExtensions; Assert.Equal(new string[] { "bmp", "gif", "jpg", "jpeg", "png", "ico" }, extensions); Assert.Same(extensions, SubBitmapEditor.BitmapExtensions); diff --git a/src/System.Windows.Forms.Primitives/tests/UnitTests/Interop/Oleaut32/VARIANTTests.cs b/src/System.Windows.Forms.Primitives/tests/UnitTests/Interop/Oleaut32/VARIANTTests.cs index 01294ac63e4..540973f716e 100644 --- a/src/System.Windows.Forms.Primitives/tests/UnitTests/Interop/Oleaut32/VARIANTTests.cs +++ b/src/System.Windows.Forms.Primitives/tests/UnitTests/Interop/Oleaut32/VARIANTTests.cs @@ -952,7 +952,6 @@ public void VARIANT_ToObject_DispatchBYREFNullData_ReturnsNull() public void VARIANT_ToObject_UNKNOWN_ReturnsExpected() { object o = new(); - nint pUnk = Marshal.GetIUnknownForObject(o); using VARIANT variant = Create(VT_UNKNOWN, (void*)Marshal.GetIUnknownForObject(o)); AssertToObjectEqual(o, variant); } @@ -5274,7 +5273,6 @@ public void VARIANT_ToObject_ARRAYVARIANTMultiDimension_ReturnsExpected() [InlineData((ushort)VT_BLOB_OBJECT)] public void VARIANT_ToObject_ARRAYNoData_ReturnsExpected(ushort vt) { - SAFEARRAY* psa = CreateSafeArray(VT_I1, Array.Empty()); using VARIANT variant = new() { vt = VT_ARRAY | (VARENUM)vt @@ -5289,7 +5287,6 @@ public void VARIANT_ToObject_ARRAYNoData_ReturnsExpected(ushort vt) [InlineData((ushort)VT_BSTR_BLOB)] public void VARIANT_ToObject_ARRAYInvalidTypeNoData_ThrowsInvalidOleVariantTypeException(ushort vt) { - SAFEARRAY* psa = CreateSafeArray(VT_I1, Array.Empty()); using VARIANT variant = new() { vt = VT_ARRAY | (VARENUM)vt @@ -5301,11 +5298,11 @@ public void VARIANT_ToObject_ARRAYInvalidTypeNoData_ThrowsInvalidOleVariantTypeE [StaFact] public void VARIANT_ToObject_ARRAYVECTOR_ThrowsInvalidOleVariantTypeException() { - SAFEARRAY* psa = CreateSafeArray(VT_I1, Array.Empty()); using VARIANT variant = new() { vt = VT_ARRAY | VT_VECTOR | VT_I4 }; + Assert.Throws(variant.ToObject); } diff --git a/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Automation/UiaTextProviderTests.cs b/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Automation/UiaTextProviderTests.cs index 27d1958cc47..99ddd2ba467 100644 --- a/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Automation/UiaTextProviderTests.cs +++ b/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Automation/UiaTextProviderTests.cs @@ -65,8 +65,6 @@ public void UiaTextProvider_GetWindowExStyle_ContainsClientedge() [StaFact] public void UiaTextProvider_RectArrayToDoubleArray_ReturnsCorrectValue() { - Mock providerMock = new(MockBehavior.Strict); - double[] expected = [0, 0, 10, 5, 10, 10, 20, 30]; using SafeArrayScope actual = UiaTextProvider.RectListToDoubleArray( [ @@ -82,22 +80,16 @@ public void UiaTextProvider_RectArrayToDoubleArray_ReturnsCorrectValue() } } -#pragma warning disable CS8625 // RectArrayToDoubleArray doesn't accept a null parameter [StaFact] public void UiaTextProvider_RectArrayToDoubleArray_NullParameter_ReturnsNull() { - Mock providerMock = new(MockBehavior.Strict); - - using SafeArrayScope actual = UiaTextProvider.RectListToDoubleArray(null); + using SafeArrayScope actual = UiaTextProvider.RectListToDoubleArray(null!); Assert.True(actual.IsEmpty); } -#pragma warning restore CS8625 [StaFact] public void UiaTextProvider_RectArrayToDoubleArray_EmptyArrayParameter_ReturnsEmptyArrayResult() { - Mock providerMock = new(MockBehavior.Strict); - using SafeArrayScope actual = UiaTextProvider.RectListToDoubleArray([]); Assert.True(actual.IsEmpty); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.Methods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.Methods.cs index fe2233e5ac3..403a1170cb4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.Methods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.Methods.cs @@ -10799,7 +10799,8 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) if (dataGridViewColumn.CellTemplate!.DefaultNewRowValue is not null && NewRowIndex != -1) { // New row needs to be un-shared before addition of new cell with a Value is not null - DataGridViewRow newRow = Rows[NewRowIndex]; + // (Accessing the indexer has this side-effect) + _ = Rows[NewRowIndex]; } int newColumnCount = Columns.Count + 1; @@ -10943,7 +10944,8 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) if (dataGridViewColumn.CellTemplate!.DefaultNewRowValue is not null && NewRowIndex != -1) { // New row needs to be un-shared before addition of new cell with a Value is not null - DataGridViewRow newRow = Rows[NewRowIndex]; + // (Accessing the indexer has this side-effect) + _ = Rows[NewRowIndex]; break; } } @@ -11550,7 +11552,8 @@ protected virtual void OnCellClick(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.ClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnClickInternal(e); } else @@ -11633,7 +11636,8 @@ protected virtual void OnCellContentClick(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.ContentClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnContentClickInternal(e); } else @@ -11657,7 +11661,8 @@ protected virtual void OnCellContentDoubleClick(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.ContentDoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnContentDoubleClickInternal(e); } else @@ -11701,7 +11706,8 @@ protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.DoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnDoubleClickInternal(e); } else @@ -11847,7 +11853,8 @@ protected virtual void OnCellMouseClick(DataGridViewCellMouseEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseClickInternal(e); } else @@ -11867,7 +11874,8 @@ protected virtual void OnCellMouseDoubleClick(DataGridViewCellMouseEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseDoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseDoubleClickInternal(e); } else @@ -11930,7 +11938,8 @@ and not DataGridViewHitTestType.HorizontalScrollBar { if (e.RowIndex >= 0 && dataGridViewCell.MouseDownUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseDownInternal(e); } else @@ -12610,7 +12619,8 @@ protected virtual void OnCellMouseEnter(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseEnterUnsharesRowInternal(e.RowIndex)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseEnterInternal(e.RowIndex); } else @@ -12632,7 +12642,8 @@ protected virtual void OnCellMouseLeave(DataGridViewCellEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseLeaveUnsharesRowInternal(e.RowIndex)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseLeaveInternal(e.RowIndex); } else @@ -12651,7 +12662,8 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseMoveUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseMoveInternal(e); } else @@ -12708,7 +12720,8 @@ protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (e.RowIndex >= 0 && dataGridViewCell.MouseUpUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; + // Accessing the indexer unshares the row + _ = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseUpInternal(e); } else @@ -14651,7 +14664,8 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int { if (element is DataGridViewRow dataGridViewRow) { - if (Events[s_rowStateChangedEvent] is DataGridViewRowStateChangedEventHandler eh && dataGridViewRow.DataGridView is not null && dataGridViewRow.Index == -1) + if (Events[s_rowStateChangedEvent] is DataGridViewRowStateChangedEventHandler + && dataGridViewRow.DataGridView is not null && dataGridViewRow.Index == -1) { dataGridViewRow = Rows[index]; } @@ -15420,7 +15434,8 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data if (dataGridViewColumn.CellTemplate!.DefaultNewRowValue is not null && NewRowIndex != -1) { // New row needs to be un-shared before addition of new cell with a Value is not null - DataGridViewRow newRow = Rows[NewRowIndex]; + // (Accessing the indexer has this side effect) + _ = Rows[NewRowIndex]; } int newColumnCount = Columns.Count + 1; @@ -15670,7 +15685,8 @@ protected override void OnKeyDown(KeyEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (dataGridViewCell.KeyDownUnsharesRowInternal(e, _ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = Rows[_ptCurrentCell.Y]; + // Accessing the indexer unshares the row + _ = Rows[_ptCurrentCell.Y]; CurrentCellInternal.OnKeyDownInternal(e, _ptCurrentCell.Y); } else @@ -15728,7 +15744,8 @@ protected override void OnKeyPress(KeyPressEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (dataGridViewCell.KeyPressUnsharesRowInternal(e, _ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = Rows[_ptCurrentCell.Y]; + // Accessing the indexer unshares the row + _ = Rows[_ptCurrentCell.Y]; CurrentCellInternal.OnKeyPressInternal(e, _ptCurrentCell.Y); } else @@ -15761,7 +15778,8 @@ protected override void OnKeyUp(KeyEventArgs e) ThrowInvalidOperationExceptionIfNull(dataGridViewCell); if (dataGridViewCell.KeyUpUnsharesRowInternal(e, _ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = Rows[_ptCurrentCell.Y]; + // Accessing the indexer unshares the row + _ = Rows[_ptCurrentCell.Y]; CurrentCellInternal.OnKeyUpInternal(e, _ptCurrentCell.Y); } else @@ -19269,11 +19287,11 @@ private void PaintBorder(Graphics g, Rectangle clipRect, Rectangle bounds) return; } - bool paintingNeeded = false; int borderWidth = BorderWidth; + // Does the clipRect intersect with the top edge? Rectangle edge = new(0, 0, bounds.Width, borderWidth); - paintingNeeded = clipRect.IntersectsWith(edge); + bool paintingNeeded = clipRect.IntersectsWith(edge); if (!paintingNeeded) { // Does the clipRect intersect with the bottom edge? @@ -19334,10 +19352,11 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor DataGridViewCell cell; DataGridViewCellStyle inheritedCellStyle = new(); DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new(), dgvabsEffective; - DataGridViewColumn? dataGridViewColumnNext = null; // first paint the visible frozen columns DataGridViewColumn? dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn? dataGridViewColumnNext; + while (dataGridViewColumn is not null) { cell = dataGridViewColumn.HeaderCell; @@ -20116,9 +20135,7 @@ protected override bool ProcessDialogKey(Keys keyData) } keyData &= ~Keys.Control; - bool ret = false; - - ret = base.ProcessDialogKey(keyData); + bool result = base.ProcessDialogKey(keyData); if (_dataGridViewState1[State1_LeavingWithTabKey] && Focused) { @@ -20127,17 +20144,14 @@ protected override bool ProcessDialogKey(Keys keyData) OnEnter(EventArgs.Empty); } - return ret; + return result; } } return base.ProcessDialogKey(keyData); } - protected bool ProcessDownKey(Keys keyData) - { - return ProcessDownKeyInternal(keyData, out bool moved); - } + protected bool ProcessDownKey(Keys keyData) => ProcessDownKeyInternal(keyData, out bool _); private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { @@ -22919,7 +22933,10 @@ protected bool ProcessNextKey(Keys keyData) return false; } - int nextScreenVisibleRowIndexTmp, nextScreenVisibleRowIndex = -1, jumpRows = 0; + int nextScreenVisibleRowIndexTmp; + int nextScreenVisibleRowIndex; + int jumpRows = 0; + if (_ptCurrentCell.Y == -1) { nextScreenVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); @@ -23178,7 +23195,9 @@ protected bool ProcessPriorKey(Keys keyData) return false; } - int previousScreenVisibleRowIndexTmp, previousScreenVisibleRowIndex = -1; + int previousScreenVisibleRowIndexTmp; + int previousScreenVisibleRowIndex; + if (_ptCurrentCell.Y == -1) { previousScreenVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); @@ -26537,7 +26556,6 @@ public void SelectAll() _noSelectionChangeCount++; try { - DataGridViewRow? dataGridViewRow = null; switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: @@ -26547,8 +26565,8 @@ public void SelectAll() int rowIndex = 0, maxRowIndex = Rows.Count; while (rowIndex < maxRowIndex) { - // un-sharing each row! - dataGridViewRow = Rows[rowIndex]; + // Accessing the indexer unshares the row. + _ = Rows[rowIndex]; int columnIndex = 0; while (columnIndex < maxColumnIndex) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewComboBoxCell.cs index 07c70ff0a5a..8dc639df56c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewComboBoxCell.cs @@ -1580,7 +1580,7 @@ private bool LookupValue(object? formattedValue, out object? value) Debug.Assert(DisplayMemberProperty is not null || ValueMemberProperty is not null || !string.IsNullOrEmpty(DisplayMember) || !string.IsNullOrEmpty(ValueMember)); - object? item = null; + object? item; if (DisplayMemberProperty is not null || ValueMemberProperty is not null) { // Now look up the item in the DataGridViewComboBoxCell datasource - this can be horribly inefficient diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewIntLinkedList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewIntLinkedList.cs index 9bfbdaaa71e..155cf66156e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewIntLinkedList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewIntLinkedList.cs @@ -71,7 +71,7 @@ public int this[int index] Debug.Assert(index >= 0); if (index != _lastAccessedIndex) { - int currentInt = this[index]; + _ = this[index]; Debug.Assert(index == _lastAccessedIndex); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRow.cs index a7e9c080916..6927fe09346 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRow.cs @@ -1419,7 +1419,6 @@ protected internal virtual void Paint( ArgumentNullException.ThrowIfNull(graphics); DataGridView dataGridView = DataGridView; - Rectangle updatedClipBounds = clipBounds; DataGridViewRow sharedRow = dataGridView.Rows.SharedRow(rowIndex); DataGridViewCellStyle inheritedRowStyle = new(); BuildInheritedRowStyle(rowIndex, inheritedRowStyle); @@ -1440,7 +1439,7 @@ protected internal virtual void Paint( } DataGridViewPaintParts paintParts = dgvrprepe.PaintParts; - updatedClipBounds = dgvrprepe.ClipBounds; + Rectangle updatedClipBounds = dgvrprepe.ClipBounds; // first paint the potential row header PaintHeader(graphics, @@ -1504,14 +1503,14 @@ protected internal virtual void PaintCells( Rectangle cellBounds = rowBounds; int cx = (dataGridView.RowHeadersVisible ? dataGridView.RowHeadersWidth : 0); bool isFirstDisplayedColumn = true; - DataGridViewElementStates cellState = DataGridViewElementStates.None; DataGridViewCell cell; DataGridViewCellStyle inheritedCellStyle = new(); - DataGridViewColumn? dataGridViewColumnNext = null; DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new(), dgvabsEffective; // first paint the potential visible frozen cells DataGridViewColumn? dataGridViewColumn = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewElementStates cellState; + DataGridViewColumn? dataGridViewColumnNext; while (dataGridViewColumn is not null) { cell = Cells[dataGridViewColumn.Index]; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.RowComparer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.RowComparer.cs index 827ce545a23..d8bcfc8a3ad 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.RowComparer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.RowComparer.cs @@ -71,7 +71,7 @@ internal int CompareObjects(object? value1, object? value2, int rowIndex1, int r return -1; } - int result = 0; + int result; if (_customComparer is null) { if (_dataGridViewSortedColumn is null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.cs index 0ecb3a5acc7..9f9c64dfad5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridViewRowCollection.cs @@ -100,7 +100,8 @@ protected ArrayList List int rowCount = Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { - DataGridViewRow dataGridViewRow = this[rowIndex]; + // Accessing this[rowIndex] will un-share the row. + _ = this[rowIndex]; } return ArrayList.Adapter(_items); @@ -2213,20 +2214,20 @@ internal void RemoveAtInternal(int index, bool force) Debug.Assert(!DataGridView.NoDimensionChangeAllowed); DataGridViewRow dataGridViewRow = SharedRow(index); - Point newCurrentCell = new(-1, -1); if (IsCollectionChangedListenedTo || dataGridViewRow.GetDisplayed(index)) { - dataGridViewRow = this[index]; // need to un-share row because dev is listening to OnCollectionChanged event or the row is displayed + _ = this[index]; // need to un-share row because dev is listening to OnCollectionChanged event or the row is displayed } dataGridViewRow = SharedRow(index); Debug.Assert(DataGridView is not null); - DataGridView.OnRemovingRow(index, out newCurrentCell, force); + DataGridView.OnRemovingRow(index, out _, force); UpdateRowCaches(index, ref dataGridViewRow, adding: false); if (dataGridViewRow.Index != -1) { _rowStates[index] = dataGridViewRow.State; + // Only detach un-shared rows, since a shared row has never been accessed by the user dataGridViewRow.DetachFromDataGridView(); } @@ -2234,7 +2235,7 @@ internal void RemoveAtInternal(int index, bool force) // Note: cannot set dataGridViewRow.DataGridView to null because this row may be shared and still be used. // Note that OnCollectionChanged takes care of calling _items.RemoveAt(index) & // _rowStates.RemoveAt(index). Can't do it here since OnCollectionChanged uses the arrays. - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, dataGridViewRow), index, 1, true, false, false, newCurrentCell); + OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, dataGridViewRow), index, 1, true, false, false, new Point(-1, -1)); } private static bool RowHasValueOrToolTipText(DataGridViewRow dataGridViewRow) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs index 4a9dd494326..ae260809a81 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/Label.cs @@ -875,7 +875,7 @@ protected Rectangle CalcImageRenderBounds(Image image, Rectangle r, ContentAlign Size pointImageSize = image.Size; int xLoc = r.X + 2; - int yLoc = r.Y + 2; + int yLoc; if ((align & WindowsFormsUtils.AnyRightAlign) != 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/LinkLabel.LinkLabelAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/LinkLabel.LinkLabelAccessibleObject.cs index d909bfee198..224fc19d68f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/LinkLabel.LinkLabelAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/Labels/LinkLabel.LinkLabelAccessibleObject.cs @@ -18,7 +18,7 @@ public LinkLabelAccessibleObject(LinkLabel owner) : base(owner) } internal override IRawElementProviderFragment.Interface? ElementProviderFromPoint(double x, double y) - => !this.IsOwnerHandleCreated(out LinkLabel? owner) + => !this.IsOwnerHandleCreated(out LinkLabel? _) ? base.ElementProviderFromPoint(x, y) : HitTest((int)x, (int)y) ?? base.ElementProviderFromPoint(x, y); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.ColumnHeaderCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.ColumnHeaderCollection.cs index 02f064a3133..53efd9c4343 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.ColumnHeaderCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.ColumnHeaderCollection.cs @@ -313,7 +313,7 @@ public virtual void Clear() // in Tile view our ListView uses the column header collection to update the Tile Information for (int colIdx = _owner._columnHeaders.Length - 1; colIdx >= 0; colIdx--) { - int w = _owner._columnHeaders[colIdx].Width; // Update width before detaching from ListView + _ = _owner._columnHeaders[colIdx].Width; // Update width before detaching from ListView _owner._columnHeaders[colIdx].OwnerListview = null; _owner._columnHeaders[colIdx].ReleaseUiaProvider(); } @@ -328,7 +328,7 @@ public virtual void Clear() { for (int colIdx = _owner._columnHeaders.Length - 1; colIdx >= 0; colIdx--) { - int w = _owner._columnHeaders[colIdx].Width; // Update width before detaching from ListView + _ = _owner._columnHeaders[colIdx].Width; // Update width before detaching from ListView if (_owner.IsHandleCreated) { PInvokeCore.SendMessage(_owner, PInvoke.LVM_DELETECOLUMN, (WPARAM)colIdx); @@ -499,7 +499,7 @@ public virtual void RemoveAt(int index) { ColumnHeader columnHeader = _owner.GetColumnHeader(index); - int w = columnHeader.Width; // Update width before detaching from ListView + _ = columnHeader.Width; // Update width before detaching from ListView // in Tile view our ListView uses the column header collection to update the Tile Information if (_owner.IsHandleCreated && _owner.View != View.Tile) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.cs index d656f327e26..5949a52df76 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ListView/ListView.cs @@ -1753,13 +1753,17 @@ public ListViewItem? TopItem ListViewItem? topItem = TopItem; if ((topItem is null) && (_topIndex == Items.Count)) - { // There's a - topItem = value; // a single item. Result of the - if (Scrollable) // message is the number of items in the list rather than an index of an item in the list. - { // This causes TopItem to return null. A side issue is that EnsureVisible doesn't do too well - EnsureVisible(0); // here either, because it causes the listview to go blank rather than displaying anything useful. - Scroll(0, value.Index); // To work around this, we force the listbox to display the first item, then scroll down to the item - } // user is setting as the top item. + { + // Result of the message is the number of items in the list rather than an index of an item in the list. + // This causes TopItem to return null. A side issue is that EnsureVisible doesn't do too well + // here either, because it causes the listview to go blank rather than displaying anything useful. + // To work around this, we force the listbox to display the first item, then scroll down to the item + // user is setting as the top item. + if (Scrollable) + { + EnsureVisible(0); + Scroll(0, value.Index); + } return; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGrid.PropertyGridAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGrid.PropertyGridAccessibleObject.cs index 0544ba7da43..d3f8c4d2b61 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGrid.PropertyGridAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGrid.PropertyGridAccessibleObject.cs @@ -80,7 +80,6 @@ public PropertyGridAccessibleObject(PropertyGrid owningPropertyGrid) : base(owni return null; case NavigateDirection.NavigateDirection_PreviousSibling: - fragmentCount = GetChildFragmentCount(); childFragmentIndex = GetChildFragmentIndex(childFragment); if (childFragmentIndex > 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyDescriptorGridEntry.cs index d17febf4324..89b75ac6e5c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -884,7 +884,7 @@ protected bool ViewEvent( transaction?.Cancel(); transaction = null; - OwnerGridView?.ShowInvalidMessage(newHandler, ex); + OwnerGridView?.ShowInvalidMessage(ex); return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.GridViewListBoxAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.GridViewListBoxAccessibleObject.cs index ace2917627a..77559636652 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.GridViewListBoxAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.GridViewListBoxAccessibleObject.cs @@ -19,7 +19,7 @@ private class GridViewListBoxAccessibleObject : ListBox.ListBoxAccessibleObject /// The owning GridViewListBox. public GridViewListBoxAccessibleObject(GridViewListBox owningGridViewListBox) : base(owningGridViewListBox) { - if (owningGridViewListBox.OwningPropertyGridView is not PropertyGridView owningPropertyGridView) + if (owningGridViewListBox.OwningPropertyGridView is null) { throw new ArgumentException(null, nameof(owningGridViewListBox)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.cs index b4344099023..3055e78b1fc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/PropertyGrid/PropertyGridInternal/PropertyGridView.cs @@ -1254,7 +1254,7 @@ public void DoubleClickRow(int row, bool toggleExpand, int type) catch (Exception ex) { SetCommitError(ErrorState.Thrown); - ShowInvalidMessage(gridEntry.PropertyLabel, ex); + ShowInvalidMessage(ex); return; } } @@ -2309,7 +2309,7 @@ private void OnListDrawItem(object? sender, DrawItemEventArgs e) } catch (FormatException ex) { - ShowFormatExceptionMessage(gridEntry.PropertyLabel, ex); + ShowFormatExceptionMessage(ex); if (DropDownListBox.IsHandleCreated) { DropDownListBox.Visible = false; @@ -3072,7 +3072,6 @@ protected override void OnMouseMove(MouseEventArgs e) // Ensure that tooltips don't display when host application is not foreground app. // Assume that we don't want to display the tooltips - HWND foregroundWindow = PInvokeCore.GetForegroundWindow(); if (PInvoke.IsChild(PInvokeCore.GetForegroundWindow(), this)) { // Don't show the tips if a dropdown is showing @@ -4666,7 +4665,7 @@ internal bool CommitValue(GridEntry entry, object? value, bool closeDropDown = t catch (Exception ex) { SetCommitError(ErrorState.Thrown); - ShowInvalidMessage(entry.PropertyLabel, ex); + ShowInvalidMessage(ex); return false; } } @@ -4739,7 +4738,7 @@ private bool CommitText(string text) catch (Exception ex) { SetCommitError(ErrorState.Thrown); - ShowInvalidMessage(currentEntry.PropertyLabel, ex); + ShowInvalidMessage(ex); return false; } @@ -4888,10 +4887,8 @@ public DialogResult ShowDialog(Form dialog) return result; } - private unsafe void ShowFormatExceptionMessage(string? propertyName, Exception? ex) + private unsafe void ShowFormatExceptionMessage(Exception? ex) { - propertyName ??= "(unknown)"; - // We have to uninstall our hook so the user can push the button! bool hooked = EditTextBox.HookMouseDown; EditTextBox.DisableMouseHook = true; @@ -4962,10 +4959,8 @@ private unsafe void ShowFormatExceptionMessage(string? propertyName, Exception? } } - internal unsafe void ShowInvalidMessage(string? propertyName, Exception? ex) + internal unsafe void ShowInvalidMessage(Exception? ex) { - propertyName ??= "(unknown)"; - // We have to uninstall our hook so the user can push the button. bool hooked = EditTextBox.HookMouseDown; EditTextBox.DisableMouseHook = true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs index 1b9cab02888..915f9675ea6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs @@ -2195,8 +2195,6 @@ private void Replace(string text, int startPosition, int selectionLen) } else { - // temp hint used to preserve the 'primary' operation hint (no side effects). - MaskedTextResultHint tempHint = hint; int testPos; foreach (char ch in text) @@ -2222,7 +2220,7 @@ private void Replace(string text, int startPosition, int selectionLen) // if length > 0 we are (re)placing the input char in the current startPosition, otherwise we are inserting the input. bool replace = length > 0; - if (PlaceChar(clonedProvider, ch, startPosition, length, replace, out tempHint)) + if (PlaceChar(clonedProvider, ch, startPosition, length, replace, out MaskedTextResultHint tempHint)) { // caretTestPos is updated in PlaceChar call. startPosition = _caretTestPos + 1; @@ -2245,19 +2243,10 @@ private void Replace(string text, int startPosition, int selectionLen) // At this point we have processed all characters from the input text (if any) but still need to // remove remaining characters from the selected text (if editable and valid chars). - if (startPosition <= endPos) + if (startPosition <= endPos + && !clonedProvider.RemoveAt(startPosition, endPos, out _caretTestPos, out MaskedTextResultHint tempHint)) { - if (!clonedProvider.RemoveAt(startPosition, endPos, out _caretTestPos, out tempHint)) - { - OnMaskInputRejected(new MaskInputRejectedEventArgs(_caretTestPos, tempHint)); - } - - // If 'replace' is not actually performed (maybe the input is empty which means 'remove', hint will be whatever - // the 'remove' operation result hint is. - if (hint == MaskedTextResultHint.NoEffect && hint != tempHint) - { - hint = tempHint; - } + OnMaskInputRejected(new MaskInputRejectedEventArgs(_caretTestPos, tempHint)); } } } @@ -2527,7 +2516,7 @@ private void SetMaskedTextProvider(MaskedTextProvider newProvider, string? textO } int testPos = 0; - bool raiseOnMaskInputRejected = false; // Raise if new provider rejects old text. + bool raiseOnMaskInputRejected; MaskedTextResultHint hint = MaskedTextResultHint.NoEffect; MaskedTextProvider oldProvider = _maskedTextProvider; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs index dc4ddfd02db..b68f7a97850 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs @@ -1006,8 +1006,7 @@ internal virtual void SetSelectedTextInternal(string? text, bool clearUndo) } /// - /// Gets or sets the number of characters selected in the text - /// box. + /// Gets or sets the number of characters selected in the text box. /// [SRCategory(nameof(SR.CatAppearance))] [Browsable(false)] @@ -1017,28 +1016,24 @@ public virtual int SelectionLength { get { - GetSelectionStartAndLength(out int start, out int length); - + GetSelectionStartAndLength(out int _, out int length); return length; } - set { ArgumentOutOfRangeException.ThrowIfNegative(value); - GetSelectionStartAndLength(out int selStart, out int selLength); + GetSelectionStartAndLength(out int start, out int length); - if (value != selLength) + if (value != length) { - Select(selStart, value); + Select(start, value); } } } /// - /// Gets or sets the starting - /// point of text selected in the text - /// box. + /// Gets or sets the starting point of text selected in the text box. /// [SRCategory(nameof(SR.CatAppearance))] [Browsable(false)] @@ -1048,21 +1043,18 @@ public int SelectionStart { get { - GetSelectionStartAndLength(out int selStart, out _); - - return selStart; + GetSelectionStartAndLength(out int start, out _); + return start; } set { ArgumentOutOfRangeException.ThrowIfNegative(value); - Select(value, SelectionLength); } } /// - /// Gets or sets - /// the current text in the text box. + /// Gets or sets the current text in the text box. /// [Localizable(true)] [AllowNull] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs index 133b88683e7..040b4ff8ef4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStrip.cs @@ -148,7 +148,6 @@ public ToolStrip() Dock = DefaultDock; AutoSize = true; CausesValidation = false; - Size defaultSize = DefaultSize; SetAutoSizeMode(AutoSizeMode.GrowAndShrink); ShowItemToolTips = DefaultShowItemToolTips; ResumeLayout(true); @@ -538,10 +537,9 @@ public override Font Font /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// - protected override Size DefaultSize - => ScaleHelper.IsThreadPerMonitorV2Aware ? - ScaleHelper.ScaleToDpi(new Size(100, 25), DeviceDpi) : - new Size(100, 25); + protected override Size DefaultSize => ScaleHelper.IsThreadPerMonitorV2Aware + ? ScaleHelper.ScaleToDpi(new Size(100, 25), DeviceDpi) + : new Size(100, 25); protected override Padding DefaultPadding { @@ -4250,7 +4248,9 @@ protected virtual void SetDisplayedItems() // For splitstack layout we re-arrange the items in the displayed items // collection so that we can easily tab through them in natural order - Rectangle displayRect = DisplayRectangle; + + // We've historically called this virtual, still need to for compat. + _ = DisplayRectangle; int lastRightAlignedItem = -1; for (int pass = 0; pass < 2; pass++) @@ -4568,12 +4568,7 @@ private void UpdateOrientation(Orientation newOrientation) { if (newOrientation != Orientation) { - // snap our last dimensions before switching over. - // use specifed bounds so that if something is docked or anchored we don't take the extra stretching - // effects into account. - Size size = CommonProperties.GetSpecifiedBounds(this).Size; Orientation = newOrientation; - // since the Grip affects the DisplayRectangle, we need to re-adjust the size SetupGrip(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs index 6d7cd50b15d..83777ba575b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs @@ -988,9 +988,7 @@ internal Rectangle GetDropDownBounds(Rectangle suggestedBounds) Rectangle dropDownBounds; if (TopLevel) { - Point screenPoint = Point.Empty; - - screenPoint = _ownerItem is ToolStripDropDownItem dropDownItem + Point screenPoint = _ownerItem is ToolStripDropDownItem dropDownItem ? dropDownItem.DropDownLocation : suggestedBounds.Location; @@ -1001,8 +999,7 @@ internal Rectangle GetDropDownBounds(Rectangle suggestedBounds) } else { - Point parentClientPoint = Point.Empty; - parentClientPoint = (_ownerItem is ToolStripDropDownItem dropDownItem) && (ParentInternal is not null) + Point parentClientPoint = (_ownerItem is ToolStripDropDownItem dropDownItem) && (ParentInternal is not null) ? ParentInternal.PointToClient(dropDownItem.DropDownLocation) : suggestedBounds.Location; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDownMenu.cs index 52c8f29362c..eb4acecf443 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDownMenu.cs @@ -346,7 +346,7 @@ private void CalculateInternalLayoutMetrics() maxTextSize.Width = Math.Max(maxTextSize.Width, maxNonMenuItemSize.Width); Point nextPoint = Point.Empty; - int checkAndImageMarginWidth = 0; + int checkAndImageMarginWidth; int extraImageWidth = Math.Max(0, maxImageSize.Width - _defaultImageSize.Width); @@ -531,10 +531,6 @@ internal override void Initialize() { base.Initialize(); Padding = DefaultPadding; - FlowLayoutSettings settings = new(this) - { - FlowDirection = FlowDirection.TopDown - }; _state[s_stateShowImageMargin] = true; } @@ -760,7 +756,6 @@ internal void ScrollInternal(bool up) if (_indexOfFirstDisplayedItem == Items.Count - 1) { Debug.Fail("We're trying to scroll down, but the top item is displayed!!!"); - delta = 0; } ToolStripItem itemTop = Items[_indexOfFirstDisplayedItem]; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropTargetManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropTargetManager.cs index d3f2f51dcc5..0a308152211 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropTargetManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropTargetManager.cs @@ -98,7 +98,7 @@ public void OnDragEnter(DragEventArgs e) public void OnDragOver(DragEventArgs e) { - IDropTarget? newDropTarget = null; + IDropTarget? newDropTarget; // If we are supporting Item Reordering // and this is a ToolStripItem - snitch it. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs index 72a0b621b6f..bf79f970dcd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs @@ -1565,17 +1565,9 @@ internal Size PreferredImageSize } } - Size imageSize = Size.Empty; - if (usingImageList) - { - imageSize = Owner?.ImageList?.ImageSize ?? Size.Empty; - } - else - { - imageSize = (image is null) ? Size.Empty : image.Size; - } - - return imageSize; + return usingImageList + ? Owner?.ImageList?.ImageSize ?? Size.Empty + : (image is null) ? Size.Empty : image.Size; } } @@ -2169,7 +2161,7 @@ public unsafe DragDropEffects DoDragDrop(object data, DragDropEffects allowedEff { if (data is not IComDataObject dataObject) { - DataObject? iwdata = null; + DataObject? iwdata; if (data is IDataObject idataObject) { iwdata = new DataObject(idataObject); @@ -3444,7 +3436,7 @@ internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, return fromPoint; } - Point toPoint = Point.Empty; + Point toPoint; Point currentToolStripItemLocation = Bounds.Location; // From: Screen diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItemCollection.cs index a1a90cc1de4..0d14ec7aea3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItemCollection.cs @@ -425,15 +425,9 @@ public void RemoveAt(int index) throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } - ToolStripItem? item = null; - if (index < Count && index >= 0) - { - item = (ToolStripItem)(InnerList[index]); - } - else - { - throw new IndexOutOfRangeException(); - } + ToolStripItem item = index >= Count || index < 0 + ? throw new IndexOutOfRangeException() + : (ToolStripItem)InnerList[index]; InnerList.RemoveAt(index); OnAfterRemove(item); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs index ddc65f5eed5..2423e03fb64 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs @@ -57,7 +57,7 @@ internal static Font DefaultFont return Control.DefaultFont; } - Font? sysFont = null; + Font? sysFont; // We need to cache the default fonts for the different DPIs. if (ScaleHelper.IsThreadPerMonitorV2Aware) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripMenuItem.cs index 3abf3fc77ba..7880654c700 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripMenuItem.cs @@ -675,7 +675,7 @@ private unsafe bool GetNativeMenuItemEnabled() } // Its a system defined bitmap. - int buttonToUse = -1; + int buttonToUse; if (info.hbmpItem == HBITMAP.HBMMENU_MBAR_CLOSE || info.hbmpItem == HBITMAP.HBMMENU_MBAR_CLOSE_D diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.ToolStripPanelRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.ToolStripPanelRowCollection.cs index 5b4374c29cb..3904524cad9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.ToolStripPanelRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.ToolStripPanelRowCollection.cs @@ -145,25 +145,10 @@ private void OnAdd(ToolStripPanelRow value) } } - public void Remove(ToolStripPanelRow value) - { - InnerList.Remove(value); - } + public void Remove(ToolStripPanelRow value) => InnerList.Remove(value); - public void RemoveAt(int index) - { - ToolStripPanelRow? item = null; - if (index < Count && index >= 0) - { - item = (ToolStripPanelRow)(InnerList[index]); - } + public void RemoveAt(int index) => InnerList.RemoveAt(index); - InnerList.RemoveAt(index); - } - - public void CopyTo(ToolStripPanelRow[] array, int index) - { - InnerList.CopyTo(array, index); - } + public void CopyTo(ToolStripPanelRow[] array, int index) => InnerList.CopyTo(array, index); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs index ffa7dc11b69..abc3e0041b2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanel.cs @@ -640,14 +640,6 @@ private void JoinControls(bool forceLayout) controlArray[i].Size = controlArray[i].PreferredSize; } - Point controlLocation = controlArray[i].Location; - - // right to left has changed while layout was deferred... - if (_state[s_stateRightToLeftChanged]) - { - controlLocation = new Point(Width - controlArray[i].Right, controlLocation.Y); - } - var toolStrip = controlArray[i] as ToolStrip; if (toolStrip is not null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelCell.cs index 90e6888c169..63da7eb9a78 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripPanelCell.cs @@ -263,7 +263,7 @@ protected override ArrangedElementCollection GetChildren() public override Size GetPreferredSize(Size constrainingSize) { ISupportToolStripPanel draggedControl = DraggedControl; - Size preferredSize = Size.Empty; + Size preferredSize; if (draggedControl.Stretch && ToolStripPanelRow is not null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackDragDropHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackDragDropHandler.cs index 4cc2f6fa33f..55cc552d5c6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackDragDropHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackDragDropHandler.cs @@ -206,31 +206,24 @@ private RelativeLocation ComparePositions(Rectangle orig, Point check) if (_owner.Orientation == Orientation.Horizontal) { int widthUnit = orig.Width / 2; - RelativeLocation relativeLocation = RelativeLocation.Left; // we can return here if we are checking abovebelowleftright, because // the left right calculation is more picky than the above/below calculation // and the above below calculation will just override this one. if ((orig.Left + widthUnit) >= check.X) { - relativeLocation = RelativeLocation.Left; - return relativeLocation; + return RelativeLocation.Left; } else if ((orig.Right - widthUnit) <= check.X) { - relativeLocation = RelativeLocation.Right; - return relativeLocation; + return RelativeLocation.Right; } } if (_owner.Orientation == Orientation.Vertical) { int heightUnit = orig.Height / 2; - RelativeLocation relativeLocation = (check.Y <= (orig.Top + heightUnit)) ? - RelativeLocation.Above - : RelativeLocation.Below; - - return relativeLocation; + return (check.Y <= (orig.Top + heightUnit)) ? RelativeLocation.Above : RelativeLocation.Below; } Debug.Fail("Could not calculate the relative position for AllowItemReorder"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackLayout.cs index c8472560596..435742d0623 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripSplitStackLayout.cs @@ -213,7 +213,7 @@ private bool LayoutHorizontal() int lastRight = _displayRectangle.Right; int lastLeft = _displayRectangle.Left; bool needsMoreSpace = false; - Size itemSize = Size.Empty; + Size itemSize; Rectangle alignedLeftItems = Rectangle.Empty; Rectangle alignedRightItems = Rectangle.Empty; @@ -238,7 +238,7 @@ private bool LayoutHorizontal() for (int j = -1; j < toolStrip.Items.Count; j++) { - ToolStripItem? item = null; + ToolStripItem? item; if (j == -1) { @@ -284,7 +284,7 @@ private bool LayoutHorizontal() // In RTL.No, Head is to the Left, Tail is to the Right if (item.Placement == ToolStripItemPlacement.Main) { - int x = _displayRectangle.Left; + int x; int y = _displayRectangle.Top; Padding itemMargin = item.Margin; @@ -358,7 +358,7 @@ private bool LayoutVertical() int lastBottom = _displayRectangle.Bottom; int lastTop = _displayRectangle.Top; bool needsMoreSpace = false; - Size itemSize = Size.Empty; + Size itemSize; Rectangle alignedLeftItems = Rectangle.Empty; Rectangle alignedRightItems = Rectangle.Empty; @@ -380,7 +380,7 @@ private bool LayoutVertical() for (int j = -1; j < ToolStrip.Items.Count; j++) { - ToolStripItem? item = null; + ToolStripItem? item; if (j == -1) { @@ -428,7 +428,7 @@ private bool LayoutVertical() { Padding itemMargin = item.Margin; int x = _displayRectangle.Left + itemMargin.Left; - int y = _displayRectangle.Top; + int y; switch (item.Alignment) { @@ -491,7 +491,7 @@ private void SetItemLocation(ToolStripItem item, Point itemLocation, Size itemSi { // overflow buttons can be placed outside the display rect. bool horizontal = (ToolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow); - Rectangle displayRect = _displayRectangle; + Rectangle itemBounds = new(itemLocation, itemSize); // in horizontal if something bleeds over the top/bottom that's ok - its left/right we care about diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs index 495f8d6caab..909fb2ae881 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs @@ -285,7 +285,7 @@ internal int MatchIndex(string text, bool complete, int startPosition) // otherwise returns -1. int index = startPosition; int matchIndex = -1; - bool found = false; + bool found; if (!complete) { @@ -295,14 +295,10 @@ internal int MatchIndex(string text, bool complete, int startPosition) // Attempt to match the string with Items[index] do { - if (complete) - { - found = Items[index]!.ToString()!.Equals(text); - } - else - { - found = Items[index]!.ToString()!.ToUpper(CultureInfo.InvariantCulture).StartsWith(text, StringComparison.Ordinal); - } + found = complete + ? Items[index]!.ToString()!.Equals(text) + : Items[index]!.ToString()!.ToUpper(CultureInfo.InvariantCulture) + .StartsWith(text, StringComparison.Ordinal); if (found) { @@ -386,8 +382,6 @@ private void SelectIndex(int index) Debug.Assert(index < _domainItems.Count && index >= -1, "SelectValue: index out of range"); if (_domainItems is null || index < -1 || index >= _domainItems.Count) { - // Defensive programming - index = -1; return; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/Binding.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/Binding.cs index d61c3fd3af3..2a04bda3885 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/Binding.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/Binding.cs @@ -963,7 +963,7 @@ internal bool PullData(bool reformat, bool force) internal bool PushData(bool force) { - object? dataSourceValue = null; + object? dataSourceValue; Exception? lastException = null; // Don't push if update mode is 'Never' (unless caller is FORCING us to push) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/BindingSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/BindingSource.cs index 0ab4535ff76..a08ef2824dc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/BindingSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/BindingSource.cs @@ -891,7 +891,7 @@ private void ParentCurrencyManager_CurrentItemChanged(object? sender, EventArgs CurrencyManager cm = (CurrencyManager)sender!; // track if the current list changed - bool currentItemChanged = true; + bool currentItemChanged; if (!string.IsNullOrEmpty(_dataMember)) { @@ -1458,7 +1458,7 @@ public virtual int Count public virtual int Add(object? value) { - int ret = -1; + int position; // Special case: If no data source has been assigned, the inner list will just // be an empty un-typed binding list. @@ -1479,9 +1479,9 @@ public virtual int Add(object? value) throw new InvalidOperationException(SR.BindingSourceItemTypeIsValueType); } - ret = List.Add(value); - OnSimpleListChanged(ListChangedType.ItemAdded, ret); - return ret; + position = List.Add(value); + OnSimpleListChanged(ListChangedType.ItemAdded, position); + return position; } public virtual void Clear() @@ -1513,7 +1513,8 @@ public virtual void Remove(object? value) public virtual void RemoveAt(int index) { - object? value = ((IList)this)[index]; + // Virtual, need to call for compat. + _ = this[index]; List.RemoveAt(index); OnSimpleListChanged(ListChangedType.ItemDeleted, index); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/ListBindingHelper.cs index 5d56a4ff76b..8291e405f4e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/ListBindingHelper.cs @@ -152,7 +152,7 @@ public static PropertyDescriptorCollection GetListItemProperties(object? list, P { return GetListItemProperties(list); } - else if (list is Type type) + else if (list is Type) { return GetListItemPropertiesByType(listAccessors, 0); } @@ -344,7 +344,7 @@ private static string GetListNameFromType(Type type) private static PropertyDescriptorCollection GetListItemPropertiesByType(PropertyDescriptor[] listAccessors, int startIndex) { - PropertyDescriptorCollection? pdc = null; + PropertyDescriptorCollection? pdc; if (listAccessors[startIndex] is null) { return new PropertyDescriptorCollection(null); @@ -380,8 +380,9 @@ private static PropertyDescriptorCollection GetListItemPropertiesByType(Property private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IEnumerable iEnumerable, PropertyDescriptor[] listAccessors, int startIndex) { - PropertyDescriptorCollection? pdc = null; + PropertyDescriptorCollection? pdc; object? subList = null; + // Walk down the tree - first try and get the value // This is tricky, because we can't do a standard GetValue - we need an instance of one of the // items in the list. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Internal/Formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Internal/Formatter.cs index c19765724a3..a0724a11370 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Internal/Formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Internal/Formatter.cs @@ -244,9 +244,7 @@ internal static class Formatter object? formattedNullValue, object? dataSourceNullValue) { - // // Strip away any use of nullable types (eg. Nullable), leaving just the 'real' types - // Type oldTargetType = targetType; @@ -255,25 +253,14 @@ internal static class Formatter sourceConverter = NullableUnwrap(sourceConverter); targetConverter = NullableUnwrap(targetConverter); - bool isNullableTargetType = (targetType != oldTargetType); - - // // Call the 'real' method to perform the conversion - // object? result = ParseObjectInternal(value, targetType, sourceType, targetConverter, sourceConverter, formatInfo, formattedNullValue); - // // On the way out, substitute DBNull with the appropriate representation of 'null' for the final target type. // For most types, this is just DBNull. But for a nullable type, its an instance of that type with no value. - // - - if (result == DBNull.Value) - { - return NullData(oldTargetType, dataSourceNullValue); - } - return result; + return result == DBNull.Value ? NullData(oldTargetType, dataSourceNullValue) : result; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElement.cs index fa1df952830..529017873e0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElement.cs @@ -161,10 +161,7 @@ public virtual void PerformLayout(IArrangedElement container, string? propertyNa OnLayout(new LayoutEventArgs(container, propertyName)); } - protected virtual void OnLayout(LayoutEventArgs e) - { - bool parentNeedsLayout = LayoutEngine.Layout(this, e); - } + protected virtual void OnLayout(LayoutEventArgs e) => LayoutEngine.Layout(this, e); protected virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index 38b3857a584..fada2341603 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -148,16 +148,11 @@ internal static Padding GetPadding(IArrangedElement element, Padding defaultPadd /// See . /// /// - internal static Rectangle GetSpecifiedBounds(IArrangedElement element) - { - if (element.Properties.TryGetValue(s_specifiedBoundsProperty, out Rectangle rectangle) - && rectangle != LayoutUtils.s_maxRectangle) - { - return rectangle; - } - - return element.Bounds; - } + internal static Rectangle GetSpecifiedBounds(IArrangedElement element) => + element.Properties.TryGetValue(s_specifiedBoundsProperty, out Rectangle rectangle) + && rectangle != LayoutUtils.s_maxRectangle + ? rectangle + : element.Bounds; /// /// Clears out the padding from the property store. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs index 5dfd0a9655b..bb9e51d2b85 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs @@ -319,7 +319,7 @@ public SizeF CurrentAutoScaleDimensions internal SizeF GetCurrentAutoScaleDimensions(HFONT fontHandle) { - var currentAutoScaleDimensions = SizeF.Empty; + SizeF currentAutoScaleDimensions; switch (AutoScaleMode) { case AutoScaleMode.Font: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs index 27f18a76b46..dd9461f611d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs @@ -633,7 +633,7 @@ private static bool TryCalculatePreferredSize(IArrangedElement container, bool m } Size preferredSizeForDocking = Size.Empty; - Size preferredSizeForAnchoring = Size.Empty; + Size preferredSizeForAnchoring; if (dock) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index c0058623770..74a8f2c10a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -116,7 +116,7 @@ private static void LayoutRow( int endIndex, Rectangle rowBounds) { - Size outSize = TryCalculatePreferredSizeRow( + TryCalculatePreferredSizeRow( containerProxy, elementProxy, startIndex, @@ -124,6 +124,7 @@ private static void LayoutRow( rowBounds, breakIndex: out int dummy, measureOnly: false); + Debug.Assert(dummy == endIndex, "EndIndex / BreakIndex mismatch."); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs index 37e3d6942d6..e7f6249b574 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/TableLayout.cs @@ -416,7 +416,7 @@ private static bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInf // try to layout the absolutely positioned element as if it were non-absolutely positioned. // In this way we can tell whether this element overlaps with others or fits on the table. - AdvanceUntilFits(maxColumns, reservationGrid, fixedElement, out colStop); + AdvanceUntilFits(maxColumns, reservationGrid, fixedElement, out _); // we have exceeded the row limit. just return if (fixedElement.RowStart >= maxRows) @@ -715,7 +715,9 @@ private static int InflateColumns(ContainerInfo containerInfo, Size proposedCons // since InitializeStrips already allocated absolutely sized columns, we can skip over them if (columnSpan > 1 || !IsAbsolutelySized(layoutInfo.ColumnStart, containerInfo.ColumnStyles)) { - int minWidth = 0, maxWidth = 0; + int minWidth; + int maxWidth; + // optimize for the case where one of the parameters is known. if ((columnSpan == 1 && layoutInfo.RowSpan == 1) && (IsAbsolutelySized(layoutInfo.RowStart, containerInfo.RowStyles))) @@ -1080,13 +1082,11 @@ private static int DistributeStyles(int cellBorderWidth, TableLayoutStyleCollect // If there's space left over, then give it to the percentage columns/rows totalPercentAllocatedSpace += remainingSpace; } - else if (remainingSpace < 0) { // If there's not enough space, then remove space from the percentage columns. // We do this by recalculating the space available. totalPercentAllocatedSpace = maxSize - totalAbsoluteAndAutoSizeAllocatedSpace - (strips.Length * cellBorderWidth); - remainingSpace = 0; } // in this case the strips fill up the remaining space. @@ -1178,7 +1178,6 @@ private static void SetElementBounds(ContainerInfo containerInfo, RectangleF dis int currentCol = 0; int currentRow = 0; bool isContainerRTL = false; - Rectangle displayRect = Rectangle.Truncate(displayRectF); if (containerInfo.Container is Control containerAsControl) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.PrintPreviewControlAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.PrintPreviewControlAccessibleObject.cs index c96849ddb03..9e1ea18194b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.PrintPreviewControlAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.PrintPreviewControlAccessibleObject.cs @@ -99,7 +99,7 @@ HRESULT IScrollProvider.Interface.Scroll(ScrollAmount horizontalAmount, ScrollAm return HRESULT.E_FAIL; } - int scrollValue = 0; + int scrollValue; if (owner._hScrollBar.Visible && horizontalAmount != ScrollAmount.ScrollAmount_NoAmount) { switch (horizontalAmount) @@ -156,7 +156,7 @@ HRESULT IScrollProvider.Interface.SetScrollPercent(double horizontalPercent, dou return HRESULT.E_FAIL; } - int scrollValue = 0; + int scrollValue; if (owner._hScrollBar.Visible && horizontalPercent >= 0 && horizontalPercent <= 100) { scrollValue = owner._hScrollBar.Minimum + (int)((owner._hScrollBar.Maximum - owner._hScrollBar.Minimum) * horizontalPercent); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Application.ParkingWindowTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Application.ParkingWindowTests.cs index 693c51d360e..80c6ca2b2d1 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Application.ParkingWindowTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Application.ParkingWindowTests.cs @@ -34,7 +34,7 @@ public void ParkingWindow_DoesNotThrowOnGarbageCollecting() Assert.Equal(RemoteExecutor.SuccessExitCode, invokerHandle.ExitCode); } - private Form InitFormWithControlToGarbageCollect() + private static Form InitFormWithControlToGarbageCollect() { Form form = new(); ComboBox comboBox = new() @@ -51,9 +51,6 @@ private Form InitFormWithControlToGarbageCollect() // Recreate ComboBox handle to set parent to ParkingWindow. comboBox.DropDownStyle = ComboBoxStyle.DropDownList; - // Lose the reference to ComboBox to allow Garbage collecting ComboBox. - comboBox = null; - return form; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/AxHostTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/AxHostTests.cs index 27ed2023e5b..6ce1b26c015 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/AxHostTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/AxHostTests.cs @@ -1703,7 +1703,7 @@ public unsafe void AxHost_GetIPictureFromPicture_InvokeEnhancedMetafile_Roundtri iPicture.get_Width(out int width).ThrowOnFailure(); iPicture.get_Height(out int height).ThrowOnFailure(); iPicture.get_Attributes(out uint attributes).ThrowOnFailure(); - iPicture.get_CurDC(out HDC hdc).Should().Be(HRESULT.E_FAIL); + iPicture.get_CurDC(out HDC _).Should().Be(HRESULT.E_FAIL); Assert.NotEqual(0u, handle); Assert.True(iPicture.get_hPal(out _).Failed); @@ -3115,17 +3115,17 @@ private class NoSuchAttribute : Attribute { } - [CustomAttribute] + [Custom] private class CustomAxHost : AxHost { public CustomAxHost(string clsid) : base(clsid) { } - [CustomAttribute] + [Custom] public event EventHandler CustomEvent; - [CustomAttribute] + [Custom] public string CustomProperty { get; set; } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs index 4ac6d1ea272..491e4be601f 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs @@ -756,7 +756,6 @@ public void BindingContext_CollectionChanged_Remove_Nop() public void BindingContext_OnCollectionChanged_Invoke_Nop() { SubBindingContext context = new(); - CollectionChangeEventHandler handler = (sender, e) => { }; context.OnCollectionChanged(null); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBox.ComboBoxChildNativeWindowTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBox.ComboBoxChildNativeWindowTests.cs index 8aa1b2c69af..3ffd865ff78 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBox.ComboBoxChildNativeWindowTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBox.ComboBoxChildNativeWindowTests.cs @@ -16,6 +16,7 @@ public void ComboBoxChildNativeWindow_GetChildAccessibleObject() foreach (object childWindowType in Enum.GetValues(childWindowTypeEnum)) { + childNativeWindow.TestAccessor().Dynamic._childWindowType = childWindowType; Assert.True(childNativeWindow.TestAccessor().Dynamic.GetChildAccessibleObject() is ComboBox.ChildAccessibleObject); } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs index f5bb1330b10..404fb1252c1 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs @@ -77,7 +77,6 @@ public void DataGridViewCellStyle_Ctor_NonEmptyDataGridViewCellStyle_Success() [Fact] public void DataGridViewCellStyle_Ctor_EmptyDataGridViewCellStyle_Success() { - NumberFormatInfo formatProvider = new(); DataGridViewCellStyle source = new(); DataGridViewCellStyle style = new(source); @@ -746,7 +745,6 @@ public void DataGridViewCellStyle_Clone_NonEmptyDataGridViewCellStyle_Success() [Fact] public void DataGridViewCellStyle_Clone_EmptyDataGridViewCellStyle_Success() { - NumberFormatInfo formatProvider = new(); DataGridViewCellStyle source = new(); DataGridViewCellStyle style = source.Clone(); @@ -813,7 +811,6 @@ public void DataGridViewCellStyle_ICloneableClone_NonEmptyDataGridViewCellStyle_ [Fact] public void DataGridViewCellStyle_ICloneableClone_EmptyDataGridViewCellStyle_Success() { - NumberFormatInfo formatProvider = new(); ICloneable source = new DataGridViewCellStyle(); DataGridViewCellStyle style = Assert.IsType(source.Clone()); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewHeaderCellTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewHeaderCellTests.cs index 30ede7d2dcc..60e988686f9 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewHeaderCellTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewHeaderCellTests.cs @@ -1015,11 +1015,8 @@ public static IEnumerable Resizable_GetTopLeftHeaderCell_TestData() { foreach (DataGridViewRowHeadersWidthSizeMode rowHeadersWidthSizeMode in Enum.GetValues(typeof(DataGridViewRowHeadersWidthSizeMode))) { - foreach (DataGridViewTriState rowResizable in Enum.GetValues(typeof(DataGridViewTriState))) - { - bool expected = columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing || rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing; - yield return new object[] { columnHeadersHeightSizeMode, rowHeadersWidthSizeMode, expected }; - } + bool expected = columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing || rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing; + yield return new object[] { columnHeadersHeightSizeMode, rowHeadersWidthSizeMode, expected }; } } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs index 6fd19519217..fc1f116d123 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs @@ -227,7 +227,6 @@ public void ListViewSubItemCollection_Add_ListViewSubItemExistsInOtherCollection ListViewItem item = new(); var collection = new ListViewItem.ListViewSubItemCollection(item); - ListViewItem otherItem = new(); var otherCollection = new ListViewItem.ListViewSubItemCollection(item); var subItem = new ListViewItem.ListViewSubItem(); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs index 56882777287..03736649527 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs @@ -30,7 +30,6 @@ public static IEnumerable Ctor_ListViewItem_String_TestData() yield return new object[] { new ListViewItem(), "reasonable", "reasonable" }; yield return new object[] { new ListViewItem() { BackColor = Color.Yellow, ForeColor = Color.Yellow, Font = SystemFonts.StatusFont }, "reasonable", "reasonable" }; - ListView listView = new(); ListViewItem item = new(); Assert.Null(item.ListView); yield return new object[] { item, "reasonable", "reasonable" }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs index bbc02406d44..262a75e9c32 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs @@ -24,7 +24,6 @@ public void PropertyManager_Ctor_Default() public void PropertyManager_Position_Set_Nop(int value) { BindingContext context = []; - BindingSource source = []; PropertyManager manager = Assert.IsType(context[new DataSource()]); manager.Position = value; Assert.Equal(0, manager.Position); @@ -34,7 +33,6 @@ public void PropertyManager_Position_Set_Nop(int value) public void PropertyManager_GetListName_Invoke_ReturnsEmpty() { BindingContext context = []; - BindingSource source = []; PropertyManager manager = Assert.IsType(context[new DataSource()]); Assert.Equal("System.Windows.Forms.Tests.PropertyManagerTests+DataSource.", manager.GetListName()); Assert.Empty(manager.GetListName(null)); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs index ad26ad877bf..e2afe514a2d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs @@ -1385,7 +1385,7 @@ public void ScrollableControl_GetTopLevel_Invoke_ReturnsExpected() public static IEnumerable OnLayout_TestData() { // The control must be passed along as separate variable in order to be disposed properly. - Control affectedControl = null; + Control affectedControl; yield return new object[] { true, null, 1, null }; yield return new object[] { true, new LayoutEventArgs(null, null), 1, null }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolTipBufferTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolTipBufferTests.cs index e398d3fd20f..b56d1a2f9bb 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolTipBufferTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolTipBufferTests.cs @@ -49,7 +49,6 @@ public void ToolTipBuffer_SetTextLonger_Success(string longer) { ToolTipBuffer buffer = default; buffer.SetText("text"); - IntPtr memory1 = buffer.Buffer; Assert.Equal("text", Marshal.PtrToStringUni(buffer.Buffer)); // Set longer. diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/WebBrowserTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/WebBrowserTests.cs index cb101068b20..35f63a118ed 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/WebBrowserTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/WebBrowserTests.cs @@ -2300,7 +2300,7 @@ public void WebBrowser_WebBrowserShortcutsEnabled_SetWithInstance_GetReturnsExpe [WinFormsFact] public void WebBrowser_AttachInterfaces_Invoke_Success() { - object nativeActiveXObject = null; + object nativeActiveXObject; try { @@ -2334,7 +2334,7 @@ public void WebBrowser_AttachInterfaces_Invoke_Success() [WinFormsFact] public void WebBrowser_AttachInterfaces_InvokeWithInstance_Success() { - object nativeActiveXObject = null; + object nativeActiveXObject; try {