12.9. Finding All Serializable Types Within an Assembly

Problem

You need to find all the serializable types within an assembly.

Solution

Instead of testing the implemented interfaces and attributes on every type, you can query the Type.Attributes property to determine whether it contains the TypeAttributes.Serializable flag, as the following method does:

public static ArrayList GetSerializableTypeNames(string asmPath)
{
    ArrayList serializableTypes = new ArrayList( );
    Assembly asm = Assembly.LoadFrom(asmPath);

    // look at all types in the assembly
    foreach(Type type in asm.GetTypes( ))
    {
        if ((type.Attributes & TypeAttributes.Serializable) == 
            TypeAttributes.Serializable)
        {
            // add the name of the serializable type
            serializableTypes.Add(type.FullName);
        }
    }

    return (serializableTypes);
}

The GetSerializableTypeNames method accepts the path of an assembly through its asmPath parameter. This assembly is searched for any serializable types, and their full names (including namespaces) are returned in an ArrayList. Note that you can just as easily return an ArrayList containing the Type object for each serializable type by changing the line of code:

serializableTypes.Add(asmType.FullName);

to:

serializableTypes.Add(asmType);

In order to use this method to display the serializable types in an assembly, use the following:

public static void FindSerializable( ) { Process current = Process.GetCurrentProcess( ); // get the path of the current module string asmPath = current.MainModule.FileName; ArrayList ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.