Christian Stewart
Christian Stewart

Reputation: 15519

How can I make a Linq extension for objects with a specific attribute?

I'm interested in making a extension for objects that have an attribute (in this case [ProtoContract]).

For example, the extension would work on:

[ProtoContract]
class myClass{
     //stuff
}

... but not on ...

class someRandomClass
{
}

The difference here is that usually you can make a extension function like this:

public static byte[] Serialize<T>(this T instance){

... but in this case I want it to only work on classes with the [ProtoContract] attribute.

Is this possible?

Upvotes: 1

Views: 82

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You won't be able to filter that with the where, you'll just have to throw an exception. Consider this:

public static byte[] Serialize<T>(this T instance)
{
    if (!Attribute.IsDefined(typeof(T), typeof(ProtoContractAttribute)))
    {
        throw new Exception(...);
    }
}

Upvotes: 2

Anders Abel
Anders Abel

Reputation: 69250

It is possible to make a runtime check with reflection inside youre Serialize method, but not to make the check compile time since attributes are not part of the type's signature.

If you want to have compile time checking you would have to use a (slightly ugly) interface with no methods instead of an attribute.

Upvotes: 4

Related Questions