Fody, Generics, and Nested Types
If you're thinking in terms of C# and you have a class defined like this:
public class Outer<t> { public class Inner { } }
Intuitively you'd think that the type Inner defines no generic parameters, but implicitly has access to the generic parameter T defined in the enclosing class. This is true so far as C# goes, but is not how the type is actually represented by the CLR.
Under the hood, nested types do not know anything about the generic parameters of the enclosing type. Instead, the actual Inner class that is generated by the compiler actually re-declares type T so that it's better to visualize these types like:
public class Outer<t> { public class Inner<t> { } }
While if this were the actual C# code, you'd get a warning that the type parameter T on Inner<t> hides the type parameter in Outer<t>, in practice, this is how the type actually exists.
In other words, the notion that the inner type gets "for free" the references to the generic parameter in the outer type is a C# language trick, but not something that exists at the IL level. Therefore, when creating nested types, you must propagate the generic parameters yourself.
Now to Fody. If you want to dynamically define the Inner type in Fody, you must re-create the generic parameters of the enclosing type. So if you have a TypeDefinition for an enclosing type, enclosingType, then to define the nested type, you'd use syntax like:
var nestedType = new TypeDefinition(enclosingType.Namespace, "Nested", TypeAttributes.NestedPublic, Context.ObjectType); foreach (var parameter in enclosingType.GenericParameters) { var newParameter = new GenericParameter(parameter.Name, ProceedClass); foreach (var constraint in parameter.Constraints) { newParameter.Constraints.Add(constraint); } nestedType.GenericParameters.Add(newParameter); } enclosingType.NestedTypes.Add(nestedType);
As you can see, we've defined the nested type and copied over all the generic parameters from the enclosing type. The nested type stands alone and apart from the enclosing type.













