0

I would like to have an extension method for any class that has a specific attribute.

For clarification, I have to do my own serialization of objects. But I want to only serialize objects that have this custom attribute. I know I can do it by inheriting from another base class, but I already have the class attribute and I think it would be more elegant, so you could always see if an object is custom serializable.

Something like:

[CustomAttribut]public MyClass{} 

MyClass o = new MyClass() ;
// should only exist if class has attribut CustomAttribut. 
O.CustomSerialize();
2
  • What have you already tried ? Commented Jun 3, 2016 at 16:02
  • I did not find a good solution. Only thing was by inheriting from another class with this extension. Commented Jun 3, 2016 at 16:07

2 Answers 2

3

Attributes are for storing metadata - values which are static and const and known at compile time. They cannot add methods/fields to your class - interfaces are for doing that. What you can do is to create an interface:

public interface ICustomSerializable{
    string CustomSerialize();
}

Another option is to separate your class from the serialization logic. The serialization would be handled by another class. For example:

public class CustomSerializer{

   public string CustomSerialize(object myObject){
       // for example if object has no CustomAttribut attribute 
       // you can throw "not serializable" exception here.

   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do you have an example for this with postsharp?
PostSharp is an overkill in this case (unless you have houndreds of classes annotated with [CustomAttribut] and you know what you're doing)
0

You cannot do that with plain .NET. It's called AOP or Aspect Oriented Programming.

There are a few third party providers, like PostSharp that offer those options.

1 Comment

That's unsatisfying, not your answer, thank you for this, I mean that there is a restriction. But I think I will use the Interface, that's ok.

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.