Vahid
Vahid

Reputation: 5444

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#?

Upvotes: 2

Views: 288

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

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;

Upvotes: 3

Related Questions