Search code examples
c#serializationconstructorattributesserializable

Make constructor to only accept objects with [Serializable] attribute in C#


I want to modify my constructor so that it only accepts objects that have the [Serializable] attribute. Here is my current constructor code:

public MyClass(object obj)
{
}

I want to change it to something like this:

public MyClass(? obj)
{
}

How can I accomplish this in C#?


Solution

  • The first thing that comes to my mind is to simplify this by allowing only objects that implement ISerializable interface:

    public MyClass(ISerializable obj)
    {
        // ...
    }
    

    But I think it's too simple, isn't it?

    Alternatively:

    public MyClass(Object obj)
    {
        if (!Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute)))
            throw new ArgumentException("The object must have the Serializable attribute.","obj");
    
        // ...
    }
    

    I think that you can even check for it by using:

    obj.GetType().IsSerializable;