New Features in C# 2.0—Limit Access: How do I do that?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

How do I do that?

Add the access modifier to either the get or the set accessor within the property, as illustrated in Example 1-9.

Example 1-9. Limiting access to property accessors

#region Using directives
 
using System;
using System.Collections.Generic;
using System.Text;
 
#endregion
 
namespace LimitPropertyAccess
{
  public class Employee
  {
    private string name;
    public Employee(string name)
    {
      this.name = name;
    }
    public string Name
    {
      get { return name; }
      protected set { name = value; }
    }
    public virtual void ChangeName(string name)
    {
      // do work here to update many records
      Name = name; // access the private accessor
      }
    }
 
  class Program
  {
    static void Main(string[ ] args)
    {
      Employee joe = new Employee("Joe");
      // other work here
      string whatName = joe.Name; // works
      // joe.Name = "Bob"; // doesn't compile
      joe.ChangeName("Bob"); // works
      Console.WriteLine("joe's name: {0}", joe.Name);
    }
  }
}

Output:

joe's name: Bob


Previous_Page_.gif Next_Page_.gif


Personal tools