Friday, October 22, 2010

Foo for Thought: 'Faking' a private readonly property in C#.

Scenario
We find ourselves wanting to implement a public readonly property.

But
We are annoyed by the fact that the internal name is different than the external.

public class C
{
   public C()
   {
      myProp = "V";
   }
   private readonly string myProp;
   public string MyProp { get { return myProp; } }
}

If you have an interface in place like this:

public interface IC
{
   string MyProp { get; }
}
public class C
{
   public C()
   {
      MyProp = "V";
   }
   // ---------------------------------------------------
   // Then as far as the rest of your code is concerned,
   // this is basically the same as if C# supported 
   // public readonly properties.
   // ---------------------------------------------------
   private readonly string MyProp;
   string IC.MyProp { get { return this.MyProp; } }
}
EOF

No comments:

Post a Comment