Franki1986
Franki1986

Reputation: 1436

Extension for class with specific attribute

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();

Upvotes: 0

Views: 85

Answers (2)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

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.

   }
}

Upvotes: 3

nvoigt
nvoigt

Reputation: 77304

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.

Upvotes: 0

Related Questions