Enforce that sub-classes must be serializable in .net

I have a class in a vb.net web API that I need to serialize sometimes. So, i marked the class as <Serializable>. Fine. However, it has a number of sub-classes at many levels. Some of these got missed (or gwet missed as new ones are added). If the element is null it's fine, but if it's not then the serialization fails:

[SerializationException] Type 'Foo.Bar' in Assembly 'Foo, Version=, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Since the serialisation is used in the background, to save a sate to recover to later, it's not always noticed immediately.

Serialization is using the BinaryFormatter in vb.net

Is there any way to mark the parent class such that all it's children (and their children, and so on) must also be serializable? I would prefer to get a compile-time error for this, rather than a run-time error.

I realised from some of the initial responses that my question wasn't clear enough. I should not have used the words parents and children since I am not so much focussed on class that inherit as members of the class

Class MyObj
  Public Property foo as new Foo
  Public Property bar as new Bar
end Class

I had expected this would require Foo and Bar to be serializable, since otherwise MyObj isn't

No, that isn't something you can enforce simply. Your best bet may be to add a unit test that discovers the subclasses via reflection and checks whether they have the attribute, failing if it is missing.

However, I would also advise don't use BinaryFormatter. I've seen way too many people get hurt by that - it ties the types and serialized data together too tightly. There are lots of better serialization options in .NET, for both text-based and binary serialization formats.

Object Serialization with Inheritance in Java, I have a class in a vb.net web API that I need to serialize sometimes. in Java, Hence, even though subclass doesn't implement Serializable interface( and if it's​  Serialize properties of derived classes. Serialization of a polymorphic type hierarchy is not supported. For example, if a property is defined as an interface or an abstract class, only the properties defined on the interface or abstract class are serialized, even if the runtime type has additional properties.

How serialization works when only subclass implements serializable , Enforce that sub-classes must be serializable in .net - .net. Your best bet may be to add a unit test that discovers the subclasses via reflection and checks  Serialization in .NET. 09/02/2019; 2 minutes to read; In this article. Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be stored and transferred.

AS per my knowledge, there is no way to enforce compile time error in this case. Alternative to this you can use Inherited Property of AttributeUsage. Create your custom Serializable attribute just to override the Inherited value. And use that instead of [Serializable].

Internal Implementation of [Serializable] attribute:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | 
AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
            public sealed class SerializableAttribute : Attribute
                // Summary:
                //     Initializes a new instance of the System.SerializableAttribute class.
                public SerializableAttribute();

Here Inherited is set to false; it means this attribute can not be inherited by derived class. Just override this property and use your custom attribute.

You can also verify the existence of certain attributes in your sub classes at run time.

By throwing custom exception will help you to identify the exact error.

class BaseClass
    public BaseClass()
        Type t = GetType();
        if (t.IsDefined(typeof(SerializableAttribute), false) == false)
            Console.WriteLine("Serializable attribute is missing on class");
            throw new InvalidOperationException("Serializable attribute is missing on class");

Everything You Need to Know About Java Serialization Explained , Hence, even though subclass doesn't implement Serializable interface( and if it's So every non-serializable superclass must necessarily contain default  The special constructor used for serialization should also perform thorough input validation and should be either protected or private to help protect against misuse by malicious code. It should enforce the same security checks and permissions required to obtain an instance of such a class by any other means, such as explicitly creating the

Why Do We Need Serialization in Java?, NET to automatically serialize the object. The only The class must be marked SerializableAttribute and implement the ISerializable interface. Apply the SerializableAttribute attribute even if the class also implements the ISerializable interface to control the serialization process. When you apply the SerializableAttribute attribute to a type, all private and public fields are serialized by default.

Enforce that sub-classes must be serializable in .net, However, you must instruct the XmlSerializer to accept the derived type when serializing or deserializing. This can be done by creating a  First, we create an object of the Tutorial class. We then assign the value of "1" to ID and ".net" to the name property. We then use the formatter class which is used to serialize or convert the object to a binary format. The data in the file in serialization is done in binary format. Next, we create a file stream object.

Enforce that sub-classes must be serializable in .net - .net - iOS, Classes that do not implement this interface will not have any of their state A no​-arg constructor must be accessible to the subclass that is serializable. I have a class library that none of the classes are marked Serializable or directly implement the ISerializable interface. If I want to use asp.net session storage with sql server, any object that is stored in session this way, must be serializable.

  • Which serializer are you using?
  • @StevenDoggart: BinaryFormatter
  • I don't know how to make it a compile-time error, but you could make a runtime error happen earlier if you in the base class's constructor check for the Serializable attribute and throw an exception if it doesn't exist. That way it will get thrown whenever a child without the attribute is instantiated.
  • If it hurts enough then you can cobble this together yourself. Use a post-build event in your main project that runs a little program you write that uses Reflection to do this check.
  • BinaryFormatter is usable for one thing only, and that is transport serialization between different parts of the application, so that all parts of the application are updated at the same time, which means you don't have different versions of the code that serializes/deserializes, and that you don't persist the serialized data so that future versions of the application have to handle old types. But then, even in this scenario there are other alternatives.
  • @LasseVågsætherKarlsen aye, it makes sense for AppDomain exchanges, but... beyond that: bad things
  • Actually, attributes can be tagged as inherited, but SerializableAttribute is not one of those (luckily).
  • You can also use the property Inherited of AttributeUsage. true if the attribute can be inherited by derived classes and overriding members; otherwise, false.