Attributes and interfaces

F

Frank Rizzo

I have an interface which has a bunch of methods defined that all the
inheriting classes will have to implement.

How can I force the inheriting classes to have a class attribute?
Something like this (except it does not compile)

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class TestAttribute : Attribute
{
public TestAttribute (string name)
{
Console.Writeline(name);
}
}

[TestAttribute()]
public interface IReport
{
public void Execute();
}

[TestAttribute("Invoice Report")]
public class CoolReport
{
public void Execute()
{
Report.Run();
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Frank,

You can place attributes on interfaces, but you can't enforce that
implementing classes declare an attribute on them. You have to make this a
runtime check, and then fail your operation (I assume) if it doesn't exist
on classes that implement the interface.
 
S

Samuel R. Neff

Can't, use a property in the interface instead (ReportName in this
case).

will be easier to program against and get data out anyways..

Sam
 
M

Mike Labosh

I have an interface which has a bunch of methods defined that all the
inheriting classes will have to implement.

How can I force the inheriting classes to have a class attribute?

This is off the top of my head without having tried it.

Could you make a class with abstract virtual methods that do the same thing?

public class Stuff {

[SomeAttribute]
public abstract void DoStuff(int toThis);
[SomeAttribute]
public abstract int GetStuff(string fromHere);
}

Or, as many of us are guilty of, you could make a template for your
interface implementation. Not a "Template Design Pattern", I mean a
template that is buried deep within C:\Program Files\Microsoft Visual Studio
2003 folder tree, so that you can add a new class to your project, and the
Add New Class dialog will display an item titled "IDoStuff Implementation".
Your template can have the class declaration, method stubs, attributes and
all.

I can never remember where VS stores its project item templates, but you
could easily do a search in "C:\Program Files\Visual Studio 2003" for *.cs
Containing Text "public class [!".

I have made a template for classes that use COM+ Enterprise Services, and it
sprinkles all the attributes in all the right places, as well as lots of
inherited overrides. All I have to do is replace the GUIDs and modify the
items I don't like for a given implementation.

It's not pretty, but it works.

--
Peace & happy computing,

Mike Labosh, MCSD MCT
Owner, vbSensei.Com
"The power to query ADSI is a power only
one has achieved, but if we work together,
I know we can discover the secrets."
-- The Emperor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top