Search code examples
c#reflectiondatacontractserializer

Use reflection to get all extended types with Serializableattriubte


Is it possible to get all extending class types which explicitly have the Serializable attribute defined in them?

[DataContract]
[KnownType("GetKnownTypes");
public abstract class BaseClass
{
    public Type[] GetKnownTypes(){
        return all classes which extend this class
        AND explicitly have the [Serializable] attribute
    }   
}

public class DoNotWant : BaseClass {}

[Serializable]
public class Want : BaseClass {}

So GetKnownTypes will return the class 'Want', as it extends BaseClass and explicitly has the attribute Serializable whilst DoNotWant does not contain the attribute Serializable explicitly

Thank you

Edit :: I don't believe IsSerializable is accurate to rely on, as it seems to always be true (I'm not sure if this is because the BaseClass is Serializable or not)


Solution

  • Untested, but something like:

    var types = typeof(BaseClass).Assembly.GetTypes().Where(t =>
        t.IsClass && t.BaseType == typeof(BaseClass)
        && Attribute.IsDefined(t, typeof(SerializableAttribute))).ToArray();