Xaisoft
Xaisoft

Reputation: 46591

What does this syntax mean in c#?

I may not have it correct, but I saw something like this above a WebMethod:

[return:(XmlElement("Class2"),IsNullable = false)]
public Class2 MEthod1()
{

}

I saw a vb version first and I used a converter to convert it to c#. I have never seen it before. It's in a vb 6 asmx file.

Upvotes: 6

Views: 504

Answers (2)

James Johnson
James Johnson

Reputation: 46047

It's an attribute target, and it's being used in your example to disambiguate usage on the return value from other elements:

// default: applies to method
[SomeAttr]
int Method1() { return 0; } 

// applies to method
[method: SomeAttr]
int Method2() { return 0; } 

// applies to return value
[return: SomeAttr]
int Method3() { return 0; } 

When creating attributes you can specify which language elements an attribute can be applied to. This is illustrated in the example below.

For a list of available targets see here:
http://msdn.microsoft.com/en-us/library/system.attributetargets.aspx

namespace AttTargsCS 
{
    // This attribute is only valid on a class.
    [AttributeUsage(AttributeTargets.Class)]
    public class ClassTargetAttribute : Attribute {
    }

    // This attribute is only valid on a method.
    [AttributeUsage(AttributeTargets.Method)]
    public class MethodTargetAttribute : Attribute {
    }

    // This attribute is only valid on a constructor.
    [AttributeUsage(AttributeTargets.Constructor)]
    public class ConstructorTargetAttribute : Attribute {
    }

    // This attribute is only valid on a field.
    [AttributeUsage(AttributeTargets.Field)]
    public class FieldTargetAttribute : Attribute {
    }

    // This attribute is valid on a class or a method.
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
    public class ClassMethodTargetAttribute : Attribute {
    }

    // This attribute is valid on any target.
    [AttributeUsage(AttributeTargets.All)]
    public class AllTargetsAttribute : Attribute {
    }

    [ClassTarget]
    [ClassMethodTarget]
    [AllTargets]
    public class TestClassAttribute {
        [ConstructorTarget]
        [AllTargets]
        TestClassAttribute() {
        }

        [MethodTarget]
        [ClassMethodTarget]
        [AllTargets]
        public void Method1() {
        }

        [FieldTarget]
        [AllTargets]
        public int myInt;

        static void Main(string[] args) {
        }
    }
}

Upvotes: 16

John Saunders
John Saunders

Reputation: 161773

It's an attribute modifying how the return value of the method is serialized into XML.

In general, the [return: Attribute] syntax is used to indicate that the attribute applies to the return value of a method.

Upvotes: 5

Related Questions