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?
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.
An attribute on the return affects (or not: see below) the return value rather than the function itself.
However, on their own, attributes have no effect. They are used by other code (including the complier) to modify the operation of the system (eg. by providing metadata). Until there is something to read that attribute it is just unused data in the assembly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With