O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required