Issue with out-variable declaration reference outside the contain block

2 days ago 3
ARTICLE AD BOX

I was implementing a small scripting language, and I stumbled upon something very weird condition.

Consider this function:

public void Run() { Dictionary<string, System.Reflection.MethodInfo> data = new(); if (!data.TryGetValue("foo", out System.Reflection.MethodInfo? methodInfo)) { throw new Exception($"Function '' not found in function map."); } MiniscriptFunctionAttribute? attribute = methodInfo.GetCustomAttribute<MiniscriptFunctionAttribute>(); methodInfo.Invoke(vm.Implementation, null); }

What I was trying to do was create a map of functions such that I could use reflection to easily reference and invoke a function. Of course, the function above uses a local map, but this was a result of me trying to distill the error down to the simplest example.

What happened is that when I went to compile this, I would get this error:

this is an image of some code

12>S:\dfs\saintaveline\MiniscriptConsole\Program.cs(39,65,39,112): error CS1061: 'MethodInfo' does not contain a definition for 'GetCustomAttribute' and no accessible extension method 'GetCustomAttribute' accepting a first argument of type 'MethodInfo' could be found (are you missing a using directive or an assembly reference?)

Which is bizarre since MethodInfo definitely has that method. What's even more bizarre is that I can literally copy/paste the line in question below the existing one, rename the second attribute to attribute2 and the error goes away!

From there, I can delete the new attribute2 and the error remains away! Even though it's the exact same code.

I hesitate to say this is a bug in C# but it's starting to feel like one. I know my explanation is probably not that great (English is not my first language) so I am linking to a video where I explain it better: https://www.youtube.com/watch?v=RP6TdRdMDUU&t=3499s

For good measure, here is the attribute class:

[AttributeUsage(AttributeTargets.Method)] public class MiniscriptFunctionAttribute : Attribute { public string Name { get; } public int ParamCount { get; } public MiniscriptFunctionAttribute(string name, int paramCount) { Name = name; ParamCount = paramCount; } }
Read Entire Article