Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid zero-length array allocations and storing them in static fields (CA1825) #10267

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions src/Microsoft.DotNet.Wpf/src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,6 @@ dotnet_diagnostic.CA1822.severity = suggestion
# CA1823: Avoid unused private fields
dotnet_diagnostic.CA1823.severity = suggestion

# CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = suggestion

# CA1834: Use StringBuilder.Append(char) for single character strings
dotnet_diagnostic.CA1834.severity = suggestion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -982,11 +982,10 @@ internal void ConnectStyleEvent(XamlClrEventNode xamlClrEventNode)

// eventSetter = new EventSetter();
//
CodeExpression[] esParams = {};
CodeVariableReferenceExpression cvreES = new CodeVariableReferenceExpression(EVENTSETTER);
CodeAssignStatement casES = new CodeAssignStatement(cvreES,
new CodeObjectCreateExpression(KnownTypes.Types[(int)KnownElements.EventSetter],
esParams));
Array.Empty<CodeExpression>()));

// eventSetter.Event = Button.ClickEvent;
//
Expand Down Expand Up @@ -3160,9 +3159,8 @@ private CodeVariableReferenceExpression GenerateAppInstance(CodeMemberMethod cmm
//
CodeObjectCreateExpression coce;
CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression(APPVAR);
CodeExpression[] ctorParams = {};

coce = new CodeObjectCreateExpression(appClassName, ctorParams);
coce = new CodeObjectCreateExpression(appClassName, Array.Empty<CodeExpression>());

CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(appClassName, APPVAR, coce);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

Expand Down Expand Up @@ -156,7 +156,6 @@ internal void GetNextAvailableRange(out int firstAvailableIndex, out int firstOc
/// <returns>Array of cells. May be empty</returns>
internal void GetSpanCells(out TableCell[] cells, out bool isLastRowOfAnySpan)
{
cells = s_noCells;
isLastRowOfAnySpan = false;

// iterate the tail of entries (if any)
Expand Down Expand Up @@ -204,10 +203,13 @@ internal void GetSpanCells(out TableCell[] cells, out bool isLastRowOfAnySpan)

_size = j + 1;
}

#if DEBUG
else
{
cells = Array.Empty<TableCell>();
}
#if DEBUG
_index = -1;
#endif // DEBUG
#endif
}

#endregion Internal Methods
Expand Down Expand Up @@ -265,8 +267,6 @@ private void InflateCapacity()
private int _size; // current size of the list
private int _index; // index used for iteration (GetFirst / GetNext)
private const int c_defaultCapacity = 8; // default capacity
private static TableCell[] s_noCells = Array.Empty<TableCell>(); // empty array RowSpanVector returns to rows that do not
// have row spanned cells
#endregion Private Fields

//------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static string GetSignature(Type type)
var sigMethod = helperType.GetMethod("GetGuidSignature", BindingFlags.Static | BindingFlags.Public);
if (sigMethod != null)
{
return (string)sigMethod.Invoke(null, new Type[] { });
return (string)sigMethod.Invoke(null, Array.Empty<Type>());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ IRawElementProviderSimple[] ITableProvider.GetColumnHeaders()
return array.ToArray();
}

return new IRawElementProviderSimple[0] ;
return Array.Empty<IRawElementProviderSimple>();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2309,7 +2309,7 @@ internal bool ClearSelectionRaiseSelectionChanging()
//
// attempt to clear selection
//
ChangeInkCanvasSelection(new StrokeCollection(), new UIElement[]{});
ChangeInkCanvasSelection(new StrokeCollection(), Array.Empty<UIElement>());

return !InkCanvasSelection.HasSelection;
}
Expand All @@ -2325,7 +2325,7 @@ internal void ClearSelection(bool raiseSelectionChangedEvent)
if ( InkCanvasSelection.HasSelection )
{
// Reset the current selection
CoreChangeSelection(new StrokeCollection(), new UIElement[] { }, raiseSelectionChangedEvent);
CoreChangeSelection(new StrokeCollection(), Array.Empty<UIElement>(), raiseSelectionChangedEvent);
}
}

Expand Down Expand Up @@ -2510,7 +2510,7 @@ private UIElement[] ValidateSelectedElements(IEnumerable<UIElement> selectedElem
{
if (selectedElements == null)
{
return new UIElement[]{};
return Array.Empty<UIElement>();
}

List<UIElement> elements = new List<UIElement>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -966,7 +966,7 @@ private CustomPopupPlacement[] AutoToolTipCustomPlacementCallback(Size popupSize
}

default:
return new CustomPopupPlacement[]{};
return Array.Empty<CustomPopupPlacement>();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ internal static DependencyProperty[] GetNoninheritableProperties(Type type)
}
else if (typeof(LineBreak).IsAssignableFrom(type))
{
return _emptyPropertyList;
return Array.Empty<DependencyProperty>();
}
else if (typeof(Floater).IsAssignableFrom(type))
{
Expand Down Expand Up @@ -560,7 +560,7 @@ internal static DependencyProperty[] GetNoninheritableProperties(Type type)
}

Invariant.Assert(false, "We do not expect any unknown elements derived directly from TextElement. Schema must have been checking for that");
return _emptyPropertyList; // to make compiler happy
return Array.Empty<DependencyProperty>(); // to make compiler happy
}

// Compares two values for equality
Expand Down Expand Up @@ -1202,9 +1202,6 @@ private static bool AreBrushesEqual(Brush brush1, Brush brush2)
UIElement.AllowDropProperty,
};

// Empty property list
private static readonly DependencyProperty[] _emptyPropertyList = new DependencyProperty[] { };

// Structural property list.
// NB: Existing code depends on these being inheritable properties.
private static readonly DependencyProperty[] _structuralCharacterProperties = new DependencyProperty[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4432,20 +4432,15 @@ internal static string[] GetDefaultAssemblyNames()
/// </summary>
internal static NamespaceMapEntry[] GetDefaultNamespaceMaps()
{
return (NamespaceMapEntry[])_defaultNamespaceMapTable.Clone();
return Array.Empty<NamespaceMapEntry>();
}

#endregion Properties

#region Data

// array of our defaultAssemblies.
private static readonly string[] _defaultAssemblies = {"WindowsBase", "PresentationCore", "PresentationFramework"};

// array of namespaceMaps the map an xmlns namespaceURI
// to the assembly and urtNamespace to search in when resolving the xml

private static readonly NamespaceMapEntry[] _defaultNamespaceMapTable = { };
private static readonly string[] _defaultAssemblies = { "WindowsBase", "PresentationCore", "PresentationFramework" };

#endregion Data
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

Expand All @@ -13,7 +13,6 @@ public class XamlMemberInvoker
{
private static XamlMemberInvoker s_Directive;
private static XamlMemberInvoker s_Unknown;
private static object[] s_emptyObjectArray = Array.Empty<object>();

private XamlMember _member;
private NullableReference<MethodInfo> _shouldSerializeMethod;
Expand Down Expand Up @@ -65,7 +64,7 @@ public virtual object GetValue(object instance)
}
else
{
return UnderlyingGetter.Invoke(instance, s_emptyObjectArray);
return UnderlyingGetter.Invoke(instance, Array.Empty<object>());
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// Description: property/pattern/event information

using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Text;
Expand Down Expand Up @@ -338,7 +338,7 @@ private static object ConvertToAutomationHeadingLevel(object value)
new AutomationPropertyInfo( null, ScrollPattern.VerticalViewSizeProperty, typeof(double), (double)100 ),
new AutomationPropertyInfo( convertToBool, ScrollPattern.HorizontallyScrollableProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToBool, ScrollPattern.VerticallyScrollableProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToElementArray, SelectionPattern.SelectionProperty, typeof(AutomationElement[]), new AutomationElement[]{} ),
new AutomationPropertyInfo( convertToElementArray, SelectionPattern.SelectionProperty, typeof(AutomationElement[]), Array.Empty<AutomationElement>()),
new AutomationPropertyInfo( convertToBool, SelectionPattern.CanSelectMultipleProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToBool, SelectionPattern.IsSelectionRequiredProperty, typeof(bool), false ),
new AutomationPropertyInfo( null, GridPattern.RowCountProperty, typeof(int), 0 ),
Expand All @@ -351,7 +351,7 @@ private static object ConvertToAutomationHeadingLevel(object value)
new AutomationPropertyInfo( convertToDockPosition, DockPattern.DockPositionProperty, typeof(DockPosition), DockPosition.None ),
new AutomationPropertyInfo( convertToExpandCollapseState, ExpandCollapsePattern.ExpandCollapseStateProperty, typeof(ExpandCollapseState), ExpandCollapseState.LeafNode ),
new AutomationPropertyInfo( null, MultipleViewPattern.CurrentViewProperty, typeof(int), 0 ),
new AutomationPropertyInfo( null, MultipleViewPattern.SupportedViewsProperty, typeof(int []), new int [0] ),
new AutomationPropertyInfo( null, MultipleViewPattern.SupportedViewsProperty, typeof(int []), Array.Empty<int>() ),
new AutomationPropertyInfo( convertToBool, WindowPattern.CanMaximizeProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToBool, WindowPattern.CanMinimizeProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToWindowVisualState, WindowPattern.WindowVisualStateProperty, typeof(WindowVisualState), WindowVisualState.Normal ),
Expand All @@ -360,11 +360,11 @@ private static object ConvertToAutomationHeadingLevel(object value)
new AutomationPropertyInfo( convertToBool, WindowPattern.IsTopmostProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToBool, SelectionItemPattern.IsSelectedProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToElement, SelectionItemPattern.SelectionContainerProperty, typeof(AutomationElement), null ),
new AutomationPropertyInfo( convertToElementArray, TablePattern.RowHeadersProperty, typeof(AutomationElement []), new AutomationElement [0] ),
new AutomationPropertyInfo( convertToElementArray, TablePattern.ColumnHeadersProperty, typeof(AutomationElement []), new AutomationElement [0] ),
new AutomationPropertyInfo( convertToElementArray, TablePattern.RowHeadersProperty, typeof(AutomationElement[]), Array.Empty<AutomationElement>()),
new AutomationPropertyInfo( convertToElementArray, TablePattern.ColumnHeadersProperty, typeof(AutomationElement[]), Array.Empty<AutomationElement>()),
new AutomationPropertyInfo( convertToRowOrColumnMajor, TablePattern.RowOrColumnMajorProperty, typeof(RowOrColumnMajor), RowOrColumnMajor.Indeterminate ),
new AutomationPropertyInfo( convertToElementArray, TableItemPattern.RowHeaderItemsProperty, typeof(AutomationElement []), new AutomationElement [0] ),
new AutomationPropertyInfo( convertToElementArray, TableItemPattern.ColumnHeaderItemsProperty, typeof(AutomationElement []), new AutomationElement [0] ),
new AutomationPropertyInfo( convertToElementArray, TableItemPattern.RowHeaderItemsProperty, typeof(AutomationElement[]), Array.Empty<AutomationElement>()),
new AutomationPropertyInfo( convertToElementArray, TableItemPattern.ColumnHeaderItemsProperty, typeof(AutomationElement[]), Array.Empty<AutomationElement>()),
new AutomationPropertyInfo( convertToToggleState, TogglePattern.ToggleStateProperty, typeof(ToggleState), ToggleState.Indeterminate ),
new AutomationPropertyInfo( convertToBool, TransformPattern.CanMoveProperty, typeof(bool), false ),
new AutomationPropertyInfo( convertToBool, TransformPattern.CanResizeProperty, typeof(bool), false ),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ internal static UiaCacheResponse[] UiaFind(SafeNodeHandle hnode, UiaFindParams f
if (requestedData == null)
{
Debug.Assert(offsets == null && treeStructures == null, "if nothin found, all out params shoud be null");
return new UiaCacheResponse[] {}; // Return empty cacheresponse, not null.
return Array.Empty<UiaCacheResponse>(); // Return empty cacheresponse, not null.
}

Debug.Assert(offsets.Length == treeStructures.Length);
Expand Down Expand Up @@ -869,7 +869,7 @@ internal static SafeTextRangeHandle [] TextPattern_GetSelection(SafePatternHandl
CheckError(RawTextPattern_GetSelection(hobj, out arr));
if (arr == null)
{
return new SafeTextRangeHandle[] { };
return Array.Empty<SafeTextRangeHandle>();
}
SafeTextRangeHandle[] result = new SafeTextRangeHandle[arr.Length];
for (int i = 0; i < arr.Length; i++)
Expand All @@ -885,7 +885,7 @@ internal static SafeTextRangeHandle[] TextPattern_GetVisibleRanges(SafePatternHa
CheckError(RawTextPattern_GetVisibleRanges(hobj, out arr));
if (arr == null)
{
return new SafeTextRangeHandle[] { };
return Array.Empty<SafeTextRangeHandle>();
}
SafeTextRangeHandle[] result = new SafeTextRangeHandle[arr.Length];
for (int i = 0; i < arr.Length; i++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ internal static UiaCoreApi.UiaCacheRequest DefaultUiaCacheRequest
{
if(_defaultUiaCacheRequest == null)
{
_defaultUiaCacheRequest = new UiaCoreApi.UiaCacheRequest(Automation.ControlViewCondition, TreeScope.Element, new AutomationProperty[] { AutomationElement.RuntimeIdProperty }, new AutomationPattern[] { }, AutomationElementMode.Full);
_defaultUiaCacheRequest = new UiaCoreApi.UiaCacheRequest(Automation.ControlViewCondition, TreeScope.Element, new AutomationProperty[] { AutomationElement.RuntimeIdProperty }, Array.Empty<AutomationPattern>(), AutomationElementMode.Full);
}
return _defaultUiaCacheRequest;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ IRawElementProviderSimple[] ISelectionProvider.GetSelection()

Accessible[] accessibles = _acc.GetSelection();
if (accessibles == null)
return new IRawElementProviderSimple[] {};
return Array.Empty<IRawElementProviderSimple>();

IRawElementProviderSimple [] rawEPS= new IRawElementProviderSimple[accessibles.Length];
for (int i=0;i<accessibles.Length;i++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ ITextRangeProvider [] ITextProvider.GetSelection()
}

if (range == null)
return new ITextRangeProvider[] { };
return Array.Empty<ITextRangeProvider>();
else
return new ITextRangeProvider[] { new WindowsRichEditRange(range, this) };
}
Expand All @@ -249,7 +249,7 @@ ITextRangeProvider [] ITextProvider.GetVisibleRanges()
ITextRange range = GetVisibleRange();

if (range == null)
return new ITextRangeProvider[] { };
return Array.Empty<ITextRangeProvider>();
else
return new ITextRangeProvider[] { new WindowsRichEditRange(range, this) };
}
Expand Down
Loading