Will the C# attributes affect C# execution or the output? - c#

Syntactically I understand how C# attributes are applied (i.e. denoted in square brackets []). But it is not obvious what effects adding attributes actually has.
For instance:
Are attributes meant to be a type of commenting?
How are these attributes handled by the C# compiler?
Will these C# attributes change the C# program execution in any way?

Attributes are not comments; they are classes that get added to the metadata of "things" in C#. By "things" I mean classes, properties, methods, etc.
An attribute absolutely can change the execution of a program... if something uses Reflection to read and act on the attributes. For example; the [DataMember] attribute will allow a DataContractSerializer to include that member in a serialized object. The [Export] attribute will be picked up by MEF code as a plugin.
There are many other examples and you can also create your own.
For far more information about attributes see: Attributes in C#

Attributes are a powerful construct that can indirectly affect the code execution. You can inspect self or other classes using Reflection and change behaviour based on the presence of certain attributes.
Take a look at the c# programming guide: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/

Related

DefaultParameterValue attribute with XmlSerializer?

We're writing a .NET 3.5 application, which uses Xml serialization of various objects.
We are basically creating an xml document from an object, and i'd like to be able to use this attribute (DefaultParameterValue) which is what .NET 4.0 is using to implement optional arguments.
I'd like the Xml generated document to contain the default values for the parameters that have this attribute.
Is it possible?
XmlSerializer operates at the (public) field/property level. In doing so, one of the things it looks at is the similar [DefaultValue(...)]. It does not look at methods at all, except for a few assistance patterns like ShouldSerialize*(). As such, there would seen to be no crossover at all with parameters, ad no need to look at [DefaultParameterValue(...)].
This is not how attributes work. The ones that xml de/serializers recognize are well documented, the list is not extensible. Adding more requires changing code. Code that you cannot change, it is locked up inside a framework assembly.
Implement the equivalent by assigning the default value you want in the class constructor.

Attributes, just metadata or needed?

Few days ago I asked what this attribute means:
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")] public unsafe static extern bool ZeroMemory(byte* destination, int length);
I have learned that attributes are metadata but what I do not understand is - is this needed in this case? I thought metada are just that, metadata that can be ommited. Also the code seems to be running fine when I remove the attibute.
I would like to understand.
PS: Hans Passant mentioned its covered by any book about .NET Csharp..it is not, the largely used one VS 2010 from John Sharp does not cover it.
The metadata does usually have a reason and a meaning. In this particular case it tells the compiler how to bind this external method definition (e.g. to which DLL import it matches).
Other attributes control how interop is performed by the framework, yet other control how the object inspector displays data. 3rd-party attributes are also used extensively to control various behaviors, for instance for finding specific type information when performing reflection.
No, this attribute is absolutely required. It informs the CLR that what you've defined actually uses platform invokation services (or, P/Invoke) to call a function defined in unmanaged code.
Specifically, the RtlZeroMemory function, defined in the library kernel32.dll.
Without it, the compiler wouldn't know which function it was bound to, and the CLR wouldn't know which function to call at run-time.
This attribute is doing 2 things
Informs the CLR that the C method being invoked lives in kernel32.dll
Informs the CLR that the C method name is RtlZeroMemory and not ZeroMemory as it's named in code.
Yes this attribute is 100% necessary. It's a requirement for any PInvoke method to at the least name the DLL the C method lives in.
As your example shows, attributes are in fact needed in several key areas of .NET programming.
Attributes provide a model known as "Aspect-Oriented Programming" or AOP. Instead of having to write code that performs some specific task, such as serialization, DLL interop, logging, etc, you can instead simply decorate the classes or members on which you want these tasks performed with an attribute. Attributes are a special type of class, with members which can be invoked by the CLR as it runs your code, that will perform the task you wanted when you decorated the code.
You are correct in part; many attributes are intended simply to store metadata. DescriptionAttribute is a good one. However, even in this case, the attribute is important depending on how it's used. If you are decorating a member of a GUI class that you want to use in the designer, [Description()] provides valuable information to the user of the class in the designer, which may not be you. I've also seen and used many alternate uses for DescriptionAttribute; it can be applied to almost anything, so I've used it to provide "friendly names" for Enum constants, coupled with a GetDescription() extension method to grab them, when using Enums to populate drop-down lists.
So, while it's technically "metadata", an attribute's being "required" is governed by how much you want the task inherent in that attribute to be performed.
As for this particular attribute, I'm not too sure. To be honest, I've never seen it in almost a year of constant C#.
However, attributes in general can prove very useful. For instance, I was having issues with the VS2010 designer setting autocomplete properties in the wrong order, and getting run-time errors as a result. The solution was to add attributes to the autocomplete properties that prevented the designer from writing these properties to the design file, and instead setting the properties myself in the .cs file (in the proper order).
Summary: Attributes (usually) are not required, but can prove extremely useful.

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.

Can a custom attribute imply other attributes without inheritance?

I'm writing some library code, and classes that use that code are required to have two attributes specified (one custom attribute and one from .NET).
It's a bit of a hassle to document this requirement and copy-and-paste both of those attributes onto every class that uses my library, so I thought it might be better to have my custom attribute just imply the presence of the other. That other attribute from the .NET framework is sealed, though, so I can't just inherit it...
So is there any way to do this? Can I maybe add the .NET attribute at runtime?
Thanks.
Whilst you can use inheritance in attributes it is recommended you don't.
Since this is only a performance rule you will not violate correctness but it can be a source of some confusion and you must spend a great deal of effort to ensure you do not violate the semantics of the base attribute. You may cause issues if you attempt to expand the possible locations for the attribute with the AttributeUsage flags. The rules for the attribute in question are quite complex.
A method can have either of the two attributes applied, but not both. Any operation that has neither applied uses the attribute applied to the containing class. If the containing class does not have either attribute applied, the DataContractSerializer is used.
Give this making it sealed sounds like a sensible plan on their part. This API is not designed with this sort of extension in mind.
There is no way (short of AOP style 'code injection') to add attributes to existing classes at runtime.
I do not believe there is a way to imply secondary attributes or to add attributes at runtime. However, you could use a custom code template to add the attributes to every class as you add them. And/or for classes that are already developed, I suspect you could write a macro that goes through each file and adds the attributes to the classes, however I have not done this in the past, so I'm not sure what it would entail, I know making a code template to add to attributes to a class declaration is relatively simple. But this only works for class you're adding from the point of template addition on. If you need to do cleanup to old classes as well, I would look into macros if you have a lot of files/classes this needs to be done for. Or do it manually if there are not too many.

Attributes in C#

I know that C# (and .NET in general) is big on attributes. However, despite the fact I have programmed in C# for many years, I haven't found myself ever using them. Would someone get me started on them, and explain where is the best to use them?
Thanks
From Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition by Andrew Troelsen
Understanding Attributed Programming
One role of a .NET compiler is to generate metadata
descriptions for all defined and referenced types. In addition to this standard metadata contained
within any assembly, the .NET platform provides a way for programmers to embed additional
metadata into an assembly using attributes. In a nutshell, attributes are nothing more than code
annotations that can be applied to a given type (class, interface, structure, etc.), member (property,
method, etc.), assembly, or module.
The idea of annotating code using attributes is not new. COM IDL provided numerous predefined
attributes that allowed developers to describe the types contained within a given COM server.
However, COM attributes were little more than a set of keywords. If a COM developer needed to
create a custom attribute, he or she could do so, but it was referenced in code by a 128-bit number
(GUID), which was cumbersome at best.
Unlike COM IDL attributes (which again were simply keywords), .NET attributes are class types
that extend the abstract System.Attribute base class. As you explore the .NET namespaces, you will
find many predefined attributes that you are able to make use of in your applications. Furthermore,
you are free to build custom attributes to further qualify the behavior of your types by creating a
new type deriving from Attribute.
Understand that when you apply attributes in your code, the embedded metadata is essentially
useless until another piece of software explicitly reflects over the information. If this is not the case,
the blurb of metadata embedded within the assembly is ignored and completely harmless.
Attribute Consumers
As you would guess, the .NET 3.5 Framework SDK ships with numerous utilities that are indeed on
the lookout for various attributes. The C# compiler (csc.exe) itself has been preprogrammed to
discover the presence of various attributes during the compilation cycle. For example, if the C#
compiler encounters the [CLSCompliant] attribute, it will automatically check the attributed item to
ensure it is exposing only CLS-compliant constructs. By way of another example, if the C# compiler
discovers an item attributed with the [Obsolete] attribute, it will display a compiler warning in the
Visual Studio 2008 Error List window.
In addition to development tools, numerous methods in the .NET base class libraries are preprogrammed
to reflect over specific attributes. For example, if you wish to persist the state of an
object to file, all you are required to do is annotate your class with the [Serializable] attribute. If
the Serialize() method of the BinaryFormatter class encounters this attribute, the object is automatically
persisted to file in a compact binary format.
The .NET CLR is also on the prowl for the presence of certain attributes. Perhaps the most
famous .NET attribute is [WebMethod]. If you wish to expose a method via HTTP requests and automatically
encode the method return value as XML, simply apply [WebMethod] to the method and the
CLR handles the details. Beyond web service development, attributes are critical to the operation of
the .NET security system, Windows Communication Foundation, and COM/.NET interoperability
(and so on).
Finally, you are free to build applications that are programmed to reflect over your own custom
attributes as well as any attribute in the .NET base class libraries. By doing so, you are essentially
able to create a set of “keywords” that are understood by a specific set of assemblies.
Applying Attributes in C#
The .NET base class library provides a number of attributes in various
namespaces. Below is a snapshot of some—but by absolutely no means all—predefined
attributes.
A Tiny Sampling of Predefined Attributes
[CLSCompliant]
Enforces the annotated item to conform to the rules of the Common
Language Specification (CLS). Recall that CLS-compliant types are
guaranteed to be used seamlessly across all .NET programming languages.
[DllImport]
Allows .NET code to make calls to any unmanaged C- or C++-based code
library, including the API of the underlying operating system. Do note that
[DllImport] is not used when communicating with COM-based software.
[Obsolete]
Marks a deprecated type or member. If other programmers attempt to use
such an item, they will receive a compiler warning describing the error of
their ways.
[Serializable]
Marks a class or structure as being “serializable,” meaning it is able to persist
its current state into a stream.
[NonSerialized]
Specifies that a given field in a class or structure should not be persisted
during the serialization process.
[WebMethod]
Marks a method as being invokable via HTTP requests and instructs the CLR
to serialize the method return value as XML.
Building Custom Attributes
The first step in building a custom attribute is to create a new class deriving from System.Attribute. Example:
// A custom attribute.
public sealed class VehicleDescriptionAttribute : System.Attribute
{
private string msgData;
public VehicleDescriptionAttribute(string description)
{
msgData = description;
}
public VehicleDescriptionAttribute() { }
public string Description
{
get { return msgData; }
set { msgData = value; }
}
}
As you can see, VehicleDescriptionAttribute maintains a private internal string (msgData)
that can be set using a custom constructor and manipulated using a type property (Description).
Beyond the fact that this class derived from System.Attribute, there is nothing unique to this class
definition.
For security reasons, it is considered a .NET best practice to design all custom attributes as sealed. In
fact, Visual Studio 2008 provides a code snippet named Attribute that will dump out a new System.
Attribute-derived class into your code window.
Attributes get more use in code targeted to other programmers or between distinct parts of a program, rather than code targeted at end users.
For example, you could use attributes to import a dll, indicate how types would interact with visual studio (designer visible, intellisense helps, debugger step-through, etc), how to serialize them, indicate a type is obsolete, describe default values, descriptions, handle COM access, etc.
Those are things that are largely invisible to the end user and that a single programmer could put elsewhere in the source code. But they're useful when only the compiled binary is available and not the source.
I like to use attributes as metadata to my code. We have created some simple attributes that let us tag who wrote what code, when, and why. This lets us have both documented changes in code and in runtime. If there are any exceptions during runtime, we can inspect the callstack, look at any attributes on the methods along the way, and track down the people responsible:
[Author("Erich", "2009/04/06", Comment = "blah blah blah")]
public void MyFunction()
{
...
}
Of course, we could use our source control to look at who checked in what code, but this I've found makes the information more available in the place where you need it. Also, if we ever change source control, that information will not be lost since it is persisted in code.
Attributes are a form of declarative programming, 'similar' to creating your UI in XAML. It 'marks' pieces of code (classes, methods, properties, whatever) with an attribute so that you can later gather all those pieces marked in a specific way and then do something standard with all of them.
Eg. Consider the scenario where you have certain sections of code that you want to run once each time your app starts. In one model of programming (non-attribute) you go to your main method and explicitly call those init methods. With attributes you simply gather all methods which you've marked with your 'init' attribute, and call them via reflection.
The same pattern holds for actions like serialization, persistence and whatnot...
I believe you mean that you do not use (or frequently use) custom defined attributes ?
In my current project, I make heavy use of custom attributes, but, the fact that you need to keep in the back of your mind, is that using attributes should not be a goal on itself.
It is a tool / purpose to get to a given solution.
I sometimes use custom attributes in combination with a weaver like PostSharp, to decorate methods where some weaving should be applied to at compile-time.
In my current project, I also use attributes to decorate certain types with additional info ... But I believe I've posted about this here before:
Cool uses of Attributes or Annotations (CLR or Java)?
I use attributes for the following:
Communicating with a plug-in architecture
Telling another framework what to do with the code (NUnit, for instance)
Adding metadata for use with other code (See PropertyGrid)
Mapping objects to databases (See Castle ActiveRecord)
When writing my own APIs to allow users to communicate metadata
In framework code to tell the debugger to skip over it
Those are off the top of my head. I use them in many other places
Attributes are very good at describing some runtime behaviour of your code that is orthoganal to the code in question. For example, in a class called Customer you would model a customer, right? But you might not want to model or describe the way a Customer object is serialized.
Adding attributes to your Customer class allows you to tell some other part of the runtime how it should deal with your Customer.
MSTest and NUnit makes use of attributes to tell the test framework how it should use classes that define test fixtures.
ASP.NET MVC uses attribute to tell the mvc framework which methods on classes it should treat as controller actions.
So, any place where you have a runtime behaviour that you wish to model attributes can be useful.
Class Attribute definition is available here
ClassInterfaceAttribute : Indicates the type of class interface to be generated for a class exposed to COM, if an interface is generated at all.
ComDefaultInterfaceAttribute : Specifies a default interface to expose to COM. This class cannot be inherited.
ComVisibleAttribute: Controls accessibility of an individual managed type or member, or of all types within an assembly, to COM.

Categories

Resources