2

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

5
  • Are you sure? That [Serializable] stuff is quite old, we have better means now. Commented Nov 25, 2017 at 23:20
  • 2
    Short answer: You cannot do this compile time. Use reflection and throw an exception at runtime. Commented Nov 25, 2017 at 23:21
  • 2
    @HenkHolterman Can you please ne more specific? Commented Nov 25, 2017 at 23:21
  • @HenkHolterman About the other means? Commented Nov 25, 2017 at 23:59
  • 1
    Google "C# serialization" and pick through the results. JSon is popular lately. Commented Nov 26, 2017 at 7:35

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

4 Comments

obj.GetType() is Reflection.
Err I mean, without using Attribute.IsDefined <_<
But my goal was to restrict it at compile time.
Well, you can't. There is absolutely NO WAY to accomplish this. You can find two good alternatives above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.