What is the method keyword used for in C#? - c#

This might be a stupid question, or oversight on my part, but..
If you type 'method' inside an attribute definition, as below:
[method: ]
public class MyClass
Visual Studio highlights the keyword. It doesn't seem to highlight it outside of an attribute as far as I can tell, and hitting F1 in VS boots you to a 404.
I've never seen this actually used, and I can't find any information on it.
Anyone know what it does?

See Disambiguating Attribute Targets (C# Programming Guide).
Basically, it's to disambiguate between attribute applied to a method and attribute applied to the return value.

This determines that the attribute that follows the method keyword applies to the specific method. You can also declare attributes that apply not only for a single method or field, but even for a entire .dll or assembly. You can type also module or assembly.

Related

A lot of fields with the same attribute

I find myself writing a lot of this kind of stuff:
[SameAttribute]
ClassA fieldA;
[SameAttribute]
ClassB fieldB;
[SameAttribute]
ClassC fieldC;
...
Is there a syntax in C# that would allow me to mark several fields with the same attribute at once? May be there are coding conventions about this situation that would make this code less verbose and more readable?
Edit: Just to clarify, I don't want every field of the class to have this attribute, there's just a lot of them.
No. You will have to apply the [SameAttribute] to each field individually.
If you want SomeAttribute to apply to all fields in a class, it might be possible to apply the attribute to the entire class. However, even if SomeAttribute is allowed to target classes, its exact behavior when doing so is dependent on the implementation of SomeAttribute. Otherwise no, you have to apply the attribute to each field individually.
In addition to the other answers above, PostSharp, which allows "aspect-oriented programming" lets you define attributes that will apply to each member in a class. You can use it to make a custom attribute that would apply your desired attribute to all of the members.
There is nothing out of the box, that I know of, but you could use a Visual Studio add-in like ReSharper to create a live template to automatically add the Attribute you wish to use when you use a certain template
http://www.jetbrains.com/resharper/features/code_templates.html

What's with using C# attributes with the 'Attribute' suffix?

I'm looking at some C# code that applies several LINQ to SQL attributes with the Attribute suffix, e.g. ColumnAttribute, instead of the plain Column that I am used to using. Is there any reason but verbosity to do this?
There is no semantic difference. Probably whoever wrote the code just preferred that notation.
It's also possible that the code was automatically generated using a tool. Code generation tools usually don't bother to strip the Attribute bit from the attribute's type name.
Most attributes end with the word Attribute, including ColumnAttribute, CLSCompliantAttribute, and SerializableAttribute. The compiler allows the last word Attribute to be omitted. It's the programmer's choice whether to add Attribute to such names or not.
The Attribute suffix, however, is merely a convention: it is perfectly valid, albeit unusual, to define an attribute, for example, as follows:
[AttributeUsage(AttributeTargets.All)]
public class Foo : Attribute {
}
just as it is to define an exception named Throwable, for example.
The attribute is called ColumnAttribute. The compiler just provides syntactic-sugar to allow you to specify them without the Attribute suffix.
There's no practical difference.
No, it's just a style decision. However, if what you're looking at is code generated using CodeDOM the presence of the suffix is expected since C# code generator will keep the full ___Attribute type name when adding an attribute.
They're syntactically the same. AFAIK there's no reason to do this unless the person in question wasn't familiar with the fact that syntax sugar in C# adds the 'Attribute' suffix automatically when adding an attribute via square brackets.
Column is simply the nickname of ColumnAttribute, and syntactically identical in functionality, and allowed by the compiler in either form.
Some people prefer to use the full name, out of habit of following the Framework Naming Guidelines, which encourage adding Attribute to custom attribute classes, or I to interface types.
If you look at the Philips Healthcare - C# Coding Standard, rule 3#122, you can see they actually want coders to add the suffix "Attribute" to attributes.
http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf
The code may be generated but the author(s) of the code generator are probably trying to create code that meets as many standards as possible.

get_PropertyName()/set_PropertyName() vs PropertyName?

I'm using reflection on the assembly of a public API I am working with along with System.CodeDOM to generate some code that will extract information through the API.
In part of my auto-generated code I am referencing the values of a number of properties of types in the API assembly. However, I keep ending up with references to properties that don't actualy exist in my generated code. I used Type.GetProperties() which from what I understand should only return public properties.
I looked into it further and found that when I had a missing property, say called SampleProperty there were instead two methods in the class called get_SampleProperty and set_SampleProperty but no actual SampleProperty property.
What's going on here? Why does intellisense treat these methods as separate methods, but when when returned through reflection they show up as a property?
I used PropertyInfo.GetProperties() which from what I understand should only return public properties.
That might be your first hang-up, the PropertyInfo class doesn't have a GetProperties method. The Type class does. Your question otherwise indicates that you are actually using Type.GetMethods(). Yes, that returns the get_Blah and set_Blah property accessor methods for a property. Under the hood, properties are actually implemented as methods.
Use Type.GetProperties() to reflect properties.

Programmatically add an attribute to a method or parameter

I can use TypeDescriptor.AddAttributes to add an attribute to a type in runtime. How do I do the same for a method and parameter? (maybe 2 separate questions...)
TypeDescriptor.AddAttributes only affects a very specific use-case; i.e. from within System.ComponentModel. For the rest of reflection, it knows nothing about the extra attribute. And indeed, System.ComponentModel doesn't really apply to methods or parameters.
So in short; you can't. You will need to store this information somewhere else (bespoke), or add it at compile-time.
As I see from analyzing the TypeDescriptor class in Reflector, the .AddAttributes method internally calls the .AddProvider method. The TypeDescriptionProvider instance passed to it is actually responsible for providing meta-data. You could try adding the [TypeDescriptionProviderAttribute] attribute to your class and implement your own provider by deriving from the TypeDescriptionProvider class. As the documentation says, by overriding TypeDescriptionProvider.CreateInstance, you could provide a substitute object whose type has all necessary attributes. I suspect that the attributes applied to methods inside the substitution type will also take effect. However, I haven't tried that myself, so feel free to experiment...

Meaning of text between square brackets

I have seen a lot of C# programs that use the [], for example [STAThread] and then the code follows. Another classic example is [DLLImport].
I know what STAThread means but my question is what is the significance of the square brackets, essentially what do they tell the compiler?
It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.
Some attributes have special meaning to the C# compiler, for instance the [Serializable] probably tells the compiler to emit some code that can serialize an instance of the class (I say 'probably' since I do not know the inner workings of the C# compiler).
You can also create your own attributes (by inheriting System.Attribute). Using reflection you could then at run-time extract information from the attributes.
A simple example would be to create an attribute to specify what kind of input field to use in a HTML form when displaying an object's property.
Some links:
Book chapter on attributes
Attributes overview (MSDN)
https://stackoverflow.com/search?q=C%23+attributes
http://www.google.com/search?q=C%23+attributes
These are attributes.
Attributes have many uses - [Obsolete] marks a method as obsolete and the compiler will warn you. Others like [DebuggerNonUserCode] tell nothing to the compiler and are there to let the debugger know that the code in the marked method is auto-generated.
You can also create your own attributes and use them to mark any kind of metadata. For example, your Customer object might have an attribute [MarketingInformation("Customer is rich! Milk him good!")].
See here for info about attributes in .Net:
http://msdn.microsoft.com/en-us/library/5x6cd29c.aspx
They are attributes, that add meta data to whatever they are decorating.
Theses are called code attributes. Attributes are used to mark code with properties which are usually designed to specify behavior during execution. They are commonly used to mark methods, properties and parameters. During execution of your code something called "reflection" will be performed to examine the code. Reflection tells the compiler to observe and obey any instructions specified by you as the coder marking attributes against the code.
A good example would be the [Serializable] attribute. This attribute when marked above a class indicates to the compiler that it can be serialized for the purposes of persisting the class instance or for transmitting across a medium such as SOAP web services.
See the following article:
link text

Categories