Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attribute to Ensure Encapsulation

I'm beginning to look into custom attributes, and I've come up with the following idea: what if I could make an attribute which would restrict the use of a variable to the property it backed?

[RestrictToProperty("Foo")]
private object _foo;
public object Foo
{
    get { return _foo; }
    set
    {
        _foo = value;
        OnFooChanged(EventArgs.Empty);
    }
}
public object NotFoo
{
    get { return _foo; }  // Warning
    set { _foo = value; } // Warning
}
public void Bar()
{
    _foo = new object();  // Warning
}

// Warning: 'MyClass._foo' should not be used outside of property 'Foo'

I believe it's possible, because Obsolete does a similar thing.

[Obsolete]
private object _foo;
public void Bar()
{
    _foo = new object(); // Warning: 'MyClass._foo' is obsolete
}

Unfortunately, I have no idea how to go about it, and can't find much beyond simple runtime attribute tutorials. Is this possible? If so, where would I start?

like image 623
dlras2 Avatar asked May 12 '26 00:05

dlras2


1 Answers

No, that is not possible. ObsoleteAttribute has a special mention in the C# specification regarding how the compiler itself responds to it.

You could implicity restrict a variables use to a single property by using auto implemented properties.

public class Test
{
  public object Foo { get; set; }
}

Edit: If you wanted special logic handled independently in the getter and setter you could try the following code. This seems awfully obnoxious to me though.

public class Test
{

  private PrivateMembers Members { get; set; }

  public object Foo
  {
    get
    {
      return Members.Foo;
    }
    set
    {
      Members.Foo = value;
      // Do something else here.
    }
  }

  private class PrivateMembers
  {
    public object Foo { get; set; }
  }
}
like image 87
Brian Gideon Avatar answered May 13 '26 13:05

Brian Gideon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!