c# using return attribute what it does?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTest
{
    class Program
    {

        static void Main(string[] args)
        {
            Test1 t1 = call();
            Console.Out.WriteLine(t1);
            Console.ReadLine();
        }

        [return: Test2(g = 5)]
        public static Test1 call()
        {
            Test1 t1 = new Test1();
            Test2 t2 = new Test2();
            return t1;

        }
    }



    class Test1 : Attribute
    {

    }

    class Test2 : Attribute
    {
        public int g;
    }
}

here the method call(), simply returns the Test1 object, but what is the purpose of setting the return attrbite with class Test2(g = 5) ?

should something change or happen? but nothing happens...can anybody explain what is going on?

how does it affect to the Test2 object? and where that object should be?

Jon Skeet
people
quotationmark

It's just an attribute, like any other - the usage of the attribute is up to whatever decides to use it. It's relatively rare to see attributes for return, but it's entirely legal, and it's just metadata which can be examined by reflection.

The C# compiler doesn't have any specific knowledge of attributes used for return as far as I'm aware, but you could use it for your own sort of code contracts, for example. As a concrete example, some frameworks include a NotNullAttribute which is somewhat-incorrectly applied to whole methods:

[NotNull] string Foo()

... to say that it won't return a null reference. I think this would be more appropriately (although less concisely) written as:

[return:NotNull] string Foo()

... to emphasize that it's the return value which is non-null, rather than that being an attribute of the overall method.

people

See more on this question at Stackoverflow