0

I'm trying to make a generic method and I want to pass an attribute when call it. Is it possibile or it's possible only on declaration?

Code:

public Window()
{
   //Is it possible do this?:
   [CustomAttribute(typeof(Something))]
   MyGenericMethod();
}

private void MyGenericMethod()
{
   //do stuff...
   //retrieve type from CustomAttribute
}

public class CustomAttribute : Attribute
{
   public CustomAttribute(Type type)
   {
   }
}
Yatimex
  • 1
  • 1
  • Attributes are a way to associate metadata with your code. If you want to pass anything to your method at runtime you should be looking at parameters and not attributes. What is it you are trying to achieve? – JonasH Jan 18 '22 at 10:13
  • I want to call MyGenericMethod that is in another class and pass a type but not through method parameter – Yatimex Jan 18 '22 at 10:26
  • But *why*? What is the end goal? Why can you not use a parameter? See [X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – JonasH Jan 18 '22 at 10:41

2 Answers2

1

The short answer is NO. An attribute is used to associate metadata, or add declarative information. So you can't call an attribute when you are invoking your method. You can read more about them here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/

I consider that you will have to review your solution for your problem and find a different approach.

D A
  • 1,724
  • 1
  • 8
  • 19
0

I don't think it's possible but you can use generic methods.

https://learn.microsoft.com/it-it/dotnet/csharp/programming-guide/generics/generic-methods