This is an add-in for Fody which lets you control the value of the localsinit
flag on methods.
This is most useful to eliminate the zero-initialization of memory returned by stackalloc
.
Roslyn now lets you control this with SkipLocalsInitAttribute
.
Prefer the compiler feature to this weaver whenever possible. See also the spec.
If you want to target frameworks prior to .NET 5, you can still use the compiler feature by defining the attribute in your own assembly:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Module
| AttributeTargets.Class
| AttributeTargets.Struct
| AttributeTargets.Interface
| AttributeTargets.Constructor
| AttributeTargets.Method
| AttributeTargets.Property
| AttributeTargets.Event, Inherited = false)]
internal sealed class SkipLocalsInitAttribute : Attribute
{
}
}
-
Install the NuGet packages
Fody
andLocalsInit.Fody
. InstallingFody
explicitly ensures the latest version is used:PM> Install-Package Fody PM> Install-Package LocalsInit.Fody
-
Add the
PrivateAssets="all"
metadata attribute to the<PackageReference />
items ofFody
andLocalsInit.Fody
in your project file, so they won't be listed as dependencies. -
If you already have a
FodyWeavers.xml
file in the root directory of your project, add the<LocalsInit />
tag there. This file will be created on the first build if it doesn't exist:<?xml version="1.0" encoding="utf-8" ?> <Weavers> <LocalsInit /> </Weavers>
See Fody usage for general guidelines, and Fody Configuration for additional options.
Add a [LocalsInit(false)]
attribute to disable the localsinit
flag at the desired level.
You can also add [LocalsInit(true)]
attributes at lower levels to override the value set at a higher level.
In practice, you'll probably want to set the default to false
at the assembly level. You can do so either as an assembly-level attribute:
[assembly: LocalsInit(false)]
Or you can set the default value in FodyWeavers.xml
:
<LocalsInit Default="false" />
Then, look in your code for usages of the stackalloc
keyword. In each case, if the code assumes the memory to be zero-initialized, add the [LocalsInit(true)]
attribute to the method, or change the code to remove that assumption.
The LocalsInit
element in FodyWeavers.xml
accepts the following attribute:
Default="true|false"
to set the default value of thelocalsinit
flag for the assembly. This is equivalent to setting an assembly-level attribute.