I want to get the approximate size of a struct that is passed as a parameter to a method. I am using a Roslyn analyzer. We want to check that structs passed in by value are not larger than 128 bytes. The use of sizeof or Marshal.SizeOf is sufficient for our purposes.
The problem is that from what I understand, I cannot use reflection to get the type in the analyzer since reflection is a runtime API. Is there any way to circumvent this issue? Or to get the approximate size of the struct from the information available in Roslyn? Here are some things I have tried so far:
private static void CheckMethodParameters(SyntaxNodeAnalysisContext context)
{
var methodDeclarationSyntax = (MethodDeclarationSyntax)context.Node;
foreach (var parameterSyntax in methodDeclarationSyntax.ParameterList.Parameters)
{
var parameterSymbol = context.SemanticModel.GetDeclaredSymbol(parameterSyntax);
if (parameterSymbol == null)
continue;
// As expected, none of these have the type I need
var entryAssembly = Assembly.GetEntryAssembly();
var callingAssembly = Assembly.GetCallingAssembly();
var executingAssemblyAssembly = Assembly.GetExecutingAssembly();
// This only gets the NamedTypeSymbol, not the type
var namedTypeSymbol = context.Compilation.GetTypeByMetadataName($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}");
// None of these work
var typeFromFullName = Type.GetType($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}, {context.Compilation.Assembly}");
var assembly = Assembly.Load(context.Compilation.Assembly.ToString());
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var type = Assembly.Load(context.Compilation.Assembly.Name).GetType($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}");
}
}
Any help would be greatly appreciated.