Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass instance of Class as parameter to Attribute constructor

I need an instance of class/model(for the purpose of accessing a non-static member) within my custom attribute.

public class LoginModel
{
     [AutoComplete(currentInstance)]  //pass instance of class or CompanyNames
     public string DepartmentName { get; set; }


     public string[] DepartmentNames { get {...} }
}

Is there a way to do this without using new() or Reflection.

like image 469
Robin Maben Avatar asked Nov 26 '10 11:11

Robin Maben


3 Answers

That's totally impossible. Attributes are baked into the metadata of the assembly at compile-time so talking about passing an instance of a class to an attribute doesn't make any sense because instances exist only at runtime.

On the other hand attributes are always consumed by reflection, so I guess that at the moment you are checking for the presence of this custom attribute on the class metadata you could use the the instance.

like image 181
Darin Dimitrov Avatar answered Oct 06 '22 01:10

Darin Dimitrov


You can only use primitives, or arrays of primitives as Attribute parameters, this is because they need to be 'in-lined' by the compiler at compile-time.

like image 37
Dean Chalk Avatar answered Oct 06 '22 00:10

Dean Chalk


Impossible man, you can't pass instance, delegate, lambda expression into the constructor of Attribute. Some discuss about it at here

like image 41
thangchung Avatar answered Oct 06 '22 01:10

thangchung