Why default constructor does not appear for value types?
- by Arun
The below snippet gives me a list of constructors and methods of a type.
static void ReflectOnType(Type type)
{
Console.WriteLine(type.FullName);
Console.WriteLine("------------");
List<ConstructorInfo> constructors =
type.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.Default).ToList();
List<MethodInfo> methods = type.GetMethods().ToList();
Type baseType = type.BaseType;
while (baseType != null)
{
constructors.AddRange(baseType.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Default));
methods.AddRange(baseType.GetMethods());
baseType = baseType.BaseType;
}
Console.WriteLine("Reflection on {0} type", type.Name);
for (int i = 0; i < constructors.Count; i++)
{
Console.Write("Constructor: {0}.{1}", constructors[i].DeclaringType.Name, constructors[i].Name);
Console.Write("(");
ParameterInfo[] parameterInfos = constructors[i].GetParameters();
if (parameterInfos.Length > 0)
{
for (int j = 0; j < parameterInfos.Length; j++)
{
if (j > 0)
{
Console.Write(", ");
}
Console.Write("{0} {1}", parameterInfos[j].ParameterType, parameterInfos[j].Name);
}
}
Console.Write(")");
if (constructors[i].IsSpecialName)
{
Console.Write(" has 'SpecialName' attribute");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < methods.Count; i++)
{
Console.Write("Method: {0}.{1}", methods[i].DeclaringType.Name, methods[i].Name);
// Determine whether or not each field is a special name.
if (methods[i].IsSpecialName)
{
Console.Write(" has 'SpecialName' attribute");
}
Console.WriteLine();
}
}
But when I pass an ‘int’ type to this method, why don’t I see the implicit constructor in the output? Or, how do I modify the above code to list the default constructor as well (in case I’m missing something in my code).