Attributes in .net [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When should I use attribute in C#?
Hi, I am trying to understand how Attributes in .net works.
As we all know Attributes are of two types metadata and context attributes.
Metadata attributes: it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and can be accessed via reflection.
Firstly, why do we need custom attributes please give examples and How is that information attached with that class and how will it be interpreted.
Custom attributes: Please explain this and explain the flow how is that custom class which is derived System.Attribute is executed and how will that information be useful to the current class or method which uses that attribute. (best example is Validation Block is applied as attributes to the property or methods and it will be automatically validated. how is this possible).
I have the basic understanding of attributes and how it works and looking at the process how that works.
Thanks in advance.

I think these tutorials might help you:
http://oreilly.com/catalog/progcsharp/chapter/ch18.html
http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx
http://www.dotnetjohn.com/articles.aspx?articleid=273

Related

How to check if a class is partial using reflection [duplicate]

This question already has answers here:
Get properties in order of declaration using reflection
(11 answers)
Closed 1 year ago.
I have a system that uses the CallerLineNumber attribute to order methods for me to retrieve them later on based on their declaration order.
This works very well, yet it does not support partial classes that are split between different files.
I do not care to support partial classes in my system, but I would like to issue an exception if someone tried to use a partial class with my system, so basically, I need a way to know if a class is declared partial, using reflection I suppose.
One idea I had was to use the CallerFilePath attribute to check that the script's attributes are all from the same file, but I was wondering if there was a simpler way.
Thank you.
At compile time attributes of partial class are merged. So, there is no way to check if class is partial via reflection (as no way also to see names of local variables, commentaries and preprocessor directives).

what are ["foo bar"] lines in c#? [duplicate]

This question already has answers here:
What are attributes in .NET?
(11 answers)
Closed 6 years ago.
So I'm coming over from Java, and I've been seeing (and using), a ton of these:
["foo bar"]
void method(param params)
{
..code things
}
Can someone explain to me what they are? I don't even know what they're called, so I can't manage to figure it out from documentation.
They are called .NET Attributes. You can read about it for example here: What are attributes in .NET?
They are called Attributes.
There are many uses, such as:
Declare tests methods
Add description on enum values
Dependency Injection with MEF
You can do things with reflection
and so on.
They are attributes. You can use them to decorate your code.
The libraries providing the attributes usually use reflection to get this decorated (meta) information from your code at runtime.
For example, the XmlSerializer uses them a lot.

C# attribute usage: only allow attributes on a property with specific data type [duplicate]

This question already has answers here:
Allow a custom Attribute only on specific type
(5 answers)
Closed 9 years ago.
I've created a few attributes for properties. now I want to limit these attributes to properties with a certain data type? the idea is, a compiler error will be thrown if it is assign to a different type. is this possible?
if not, then I guess i'll have to check it on runtime.
You could write a custom FxCop/ Code Analysis rule to check for this.
FxCop is integrated in VS 2010 under the name "Code Analyis", you can change the ruleset in the project properties.
No, this is not possible.
A good workaround is to build a unit test which will traverse all classes, their properties and check for this additional applicability criteria. It's not that comfortable as a compile-time error message, but will serve the purpose. In case you have some kind of build automation infrastructure, the quality assurance level will be the same in practice.

How to make .NET attribute only valid on certain types [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Specify required base class for .NET attribute targets
I want to specify that my custom attribute only be valid on certain types (based on interface or base class).
Like this:
How can I do that?
It sounds like you want to create an Attribute which can only be applied to certain types in much the way that AttributeUsage can only be applied to types deriving from Attribute. Introducing this type of custom restriction is simply not possible. The particular error you're seeing is not because of a custom restriction, it's one that's simply hard wired into the compiler itself.
I don't think you can, you can only specify on which kind of language element the attribute is valid. AttributeUsageAttribute is a special case, because the compiler is aware of it and doesn't let you apply it on something that is not an attribute

When should I use attribute in C#?

I saw some of the examples of utilize attribute, e.g.
(as a map for dynamic factory)
http://msdn.microsoft.com/en-us/magazine/cc164170.aspx
Just wondering what is the advantage of using attribute?
I can find the reference on http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx
however, I am not sure when and why should I try to use it.
In the .NET Framework, attributes can be used for many reasons -- like
Defining which classes are
serializable
Choosing which methods are exposed in
a Web service
Attributes allow us to add descriptions to classes, properties, and methods at design time that can then be examined at runtime via reflection.
Consider this example:
Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.
public class AccountsManager
{
[Obsolete("prefer GetAccountsList", true)]
static Account[] GetAccounts( ) { }
static List<Account> GetAccountsList( ) { }
}
If an obsolete method is used when the program is compiled, the developer gets this info and decides accordingly.
AccountManager.GetAccounts() is obsolete:
prefer GetAccountsList
We may also create and add Custom Attributes as per requirements.
Reference :
Using Attributes in C#
Hope this helps
My recommendation: use attributes to state facts about mechanisms, but not to model aspects of your business domain.
More details:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/properties-vs-attributes
Attributes are appropriate when you want to attach metadata to your classes or class members, as well as when applying a common behaviour without having to implement a certain interface for each unit that shares the behaviour. The latter is an example of aspect-oriented programming.
Consider an attribute as metadata about the method or property it belongs to. It tells something more about a member.
The .NET Framework predefines and uses attribute types to control run-time behavior of the application.
Consider [webmethod] attribute, at runtime framework resolves this attribute and determine this method going to be exposed in a webservice.
The same way, you can write your custom attributes to control the behaviour of your application at runtime. Attributes can target classes,methods,properties,delegate, enum, event, field...
To resolve the attribute at runtime, you must use reflection.
Checkout the MSDN link for more details.

Categories

Resources