cecil icon indicating copy to clipboard operation
cecil copied to clipboard

Constant type misidentified as primitive

Open SteveGilham opened this issue 2 years ago • 0 comments

The following code

namespace NullConst {

    public class Program {
        public static void Main ()
        {
            new Program ().MakeConst ();
        }

        public void MakeConst ()
        {
            const IList<string> thing = null;
        }
    }
}

compiles to IL which does not contain the const value; but it is present in the debug metadata.

Reading and then immediately writing the assembly fails with an NRE claiming that there is a null primitive constant; when stepping through the process, the type information is correctly preserved in the debug metadata (still IList<string>, with element type GenericInst). the method SignatureWriter GetConstantSignature (ElementType type, object value), however, sends this to the default primitive case where the null value fails.

The following reformulation of that method

		private SignatureWriter GetConstantSignature (ElementType type, object value)
		{
			var signature = CreateSignatureWriter ();

			if (type == ElementType.String) {
				signature.WriteConstantString ((string)value);
			} else if (type.IsPrimitive ()) {
				signature.WriteConstantPrimitive (value);
			} else {
				signature.WriteInt32 (0);
			}

			return signature;
		}

passes the unit tests, and permits the assembly to be written.

SteveGilham avatar Sep 13 '22 09:09 SteveGilham