How to Resolve Error "CS0647: Error emitting 'attribute' attribute -- 'reason'" in C#
The Compiler Error CS0647 is a metadata generation error. The message reads: "Error emitting 'MyAttribute' attribute -- 'Specific Reason'".
In C#, Attributes are metadata attached to your code (classes, methods, assemblies). When you compile your project, these attributes are serialized (converted into bytes) and stored in the assembly's manifest. CS0647 occurs when the compiler successfully parses your code, but fails during the final step of writing the attribute data into the binary.
This is usually caused by invalid data types in the attribute arguments, security permission issues, or file system locks preventing the write operation.
Understanding Attribute Emission
Attributes in .NET are special. Unlike normal objects created at runtime, attribute instances are "baked" into the DLL at compile-time. This means the arguments you pass to an attribute constructor must be:
- Constants: Strings, numbers,
typeofexpressions, or enums. - Serializable: The compiler must know how to convert the value into a binary format stored in the metadata tables.
If you provide a value that looks valid in C# syntax but cannot be physically written to the metadata (e.g., a complex object that doesn't marshal correctly, or a security attribute with invalid flags), the emission process fails.
Scenario 1: Invalid Argument Types (Non-Constant/Marshaling)
While the compiler catches most non-constant arguments with other errors (like CS0182), complex scenarios involving arrays or object types can slip through to the emission phase, causing CS0647.
Example of error
Trying to pass a multidimensional array or a jagged array where a simple 1D array is expected, or passing values that cannot be serialized.
using System;
[AttributeUsage(AttributeTargets.All)]
public class MatrixAttribute : Attribute
{
// Attributes usually support 1D arrays, but complex structures can fail emission
public MatrixAttribute(object data) { }
}
public class Program
{
// ⛔️ Error CS0647: Error emitting 'MatrixAttribute' attribute
// The compiler struggles to serialize a 2D array into attribute metadata.
[Matrix(new int[,] { { 1, 2 }, { 3, 4 } })]
static void Main() { }
}
Solution: Simplify Arguments
Stick to the standard types allowed in attribute parameters: simple types, string, Type, enums, and single-dimensional arrays of these types.
public class Program
{
// ✅ Correct: Use a flattened 1D array
[Matrix(new int[] { 1, 2, 3, 4 })]
static void Main() { }
}
Scenario 2: Security and Crypto Attributes
This error frequently appears when using attributes from System.Security.Permissions or System.Runtime.CompilerServices.InternalsVisibleTo with malformed arguments.
Case A: Strong Name Key Issues
If you use [InternalsVisibleTo], you might need to provide a public key. If the key string is malformed (contains invalid hex characters or is the wrong length), the emission fails.
using System.Runtime.CompilerServices;
// ⛔️ Error CS0647: Error emitting attribute -- 'Invalid public key'
[assembly: InternalsVisibleTo("MyFriendAssembly, PublicKey=BAD_KEY_DATA...")]
Fix: Ensure the Public Key string is a valid, full hex string extracted using the sn -p and sn -tp tools.
Case B: Security Actions
Using SecurityAction flags incorrectly can trigger this.
using System.Security.Permissions;
// ⛔️ Error CS0647: SecurityAction.Demand is not valid for assembly-level attributes.
[assembly: SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
Fix: Use the correct action scope (e.g., SecurityAction.RequestMinimum for assemblies, SecurityAction.Demand for methods).
// ✅ Correct: Appropriate action for assembly scope
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]
Scenario 3: File Locking and Permission Issues
Sometimes, the code is perfect, but the Operating System prevents the compiler from modifying the output file (the assembly being built).
The Cause
- Antivirus: Scanning the output DLL while the compiler tries to write metadata.
- Running Process: The application is running in the background and has locked the file.
- Permissions: You are building to a folder where you don't have Write access.
Solution
- Clean and Rebuild: Force a cleanup of the
binandobjfolders. - Check Processes: Ensure
MyApp.exeis not running in Task Manager. - Check Antivirus: Whitelist your project directory.
Conclusion
CS0647 means the "Save" operation for your attributes failed.
- Read the Reason: The error message usually contains specific details after the
--(e.g., "Invalid public key" or "The binary form of an attribute was invalid"). - Check Arguments: Ensure you are passing simple, serializable constants to the attribute.
- Check Security: If using
InternalsVisibleToorSecurityPermission, verify the syntax of keys and flags.