Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attributes creating fields in C#

Tags:

c#

attributes

Alright, so after a few hours of me playing around to no avail, I built a model:

[AttributeUsage(AttributeTargets.All)]
public class PublicAttribute : System.Attribute
{
    public enum Access { Public, Private }
    public PublicAttribute(string Name, Access acs)
    {
    }
    public PublicAttribute(string Name, Access acs, Action get, Action set)
    {
    }
}

So that if somebody were to do something like this:

[Public("PublicProperty", PublicAttribute.Access.Public)]
private string PrivateProperty = "hello";

or

[Public("PublicProperty", PublicAttribute.Access.Public, ()=>{return PrivateProperty;}, ()=>{PrivateProperty = value})]
private string PrivateProperty = "hello";

and then if somebody was trying to access PrivateProperty, they could just go:

ContainingClass.PublicProperty = //ect

"PublicProperty". and that is because of the attribute, and it would use those get/set accessors.

What I'd like to know:

  1. Is this even possible?
  2. Is there something that already does this?
  3. If its possible, (even if there is something else) How do i do this?
like image 816
caesay Avatar asked Jan 29 '26 17:01

caesay


2 Answers

Basically no to all 3, as C# is a strongly typed language. Even with duck typing what you're trying to achieve doesn't fit the language.

The attributes you've written allow you to interrogate the properties that have those attributes in the class, but you still need to use Reflection to discover which properties of the attribute class are set. The syntax you want to use is checked at compile-time.

like image 104
Chris S Avatar answered Feb 01 '26 07:02

Chris S


No, this is not possible using attributes. Properties are part of the class metadata emitted by the C# compiler, and the C# compiler does not consider custom attributes.

You may be able to do this by using a post-processor such as PostSharp, which can rewrite your assembly after the fact, and can be instructed to consider custom attributes. However, you still wouldn't be able to include a delegate in the attribute: the set of types that can be stored in attribute state is extremely limited.

like image 28
itowlson Avatar answered Feb 01 '26 05:02

itowlson