views:

124

answers:

2

I'm not even sure what this principle is called or how to search for it, so I sincerely apologize if it has been brought up before, but the best way to do it is with an example.

class Properties
{
  public string Name { get; set; }
}

class MyClass
{
    class SubProperties: Properties
    {
        public override Name
        {
            get { return GetActualName(); }
            set { SetActualName(value); }
        }
    }

    public SubProperties ClassProperties;

    private string GetActualName()
    {
        return SomeFunction();
    }

    private void SetActualName(string s)
    {
        ClassProperties.Name = SomeOtherFunction(s);
    }
}

The idea is to have any object that instantiates MyClass have a fully accessible property ClassProperties. To that object, it would look exactly like a Properties object, but behind the scenes, MyClass is actually computing and modifying the results of the fields. This method of declaration is obviously wrong since I can't access GetActualName() and SetActualName() from within the SubProperties definition. How would I achieve something like this?

A: 
public virtual string Name { get; set; }
zxcvbnm
+2  A: 

Are you looking for something like this?

abstract class Properties
{
    public abstract string Name { get; set; }
}

class MyClass
{
    private class SubProperties : Properties
    {
        private MyClass myClass;

        public SubProperties(MyClass myClass)
        {
            this.myClass = myClass;
        }

        public override Name
        {
            get { return this.myClass.GetActualName(); }
            set { this.myClass.SetActualName(value); }
        }
    }

    private string name;

    public MyClass
    {
        this.MyClassProperties = new SubProperties(this);
    }

    public Properties MyClassProperties { get; private set; }

    private string GetActualName()
    {
        return this.name;
    }

    private void SetActualName(string s)
    {
        this.name = s;
    }
}

You need to pass a reference to a MyClass instance to the SubProperties instance if you want to access MyClass methods from SubProperties.

dtb
This looks like what I'm after, I'll give it a shot. The only real difference is that in my case there is no private variable "name" in MyClass - it's actually reading/writing to a socket but I want to hide that completely from the calling object.Thanks!
Diego
Perfect. That did the trick.
Diego