views:

33

answers:

2

A simple example. alt text

A have a class TDMReader which is a buldier of TDMFile objects and I am using Auto Implemented Properties f.e.

    public string Name
    {
        get;
        set;
    }

    public Group[] Groups
    {
        get;
        set;
    }  

What I want to do is to make setter accessible only for TDMReader methods. In C++ i could have friends methods to access private variables, in Java I could make them in one packet and so access to fields. I have some ideas but with this auto-implemetation is a bit more complicated to do. Any ideas with a nite solution?:)

+2  A: 

Like this:

public string Name
{
    get;
    private set;
}

public Group[] Groups
{
    get;
    private set;
}  

By adding the private keyword, the setters will only be accessible by code in the same class. You can also add internal to make it accessible to code in the same project.


Note that exposing an array as a property is extremely poor design.
Instead, you should expose a Collection<Group> or ReadOnlyCollection<Group>, in the System.Collections.ObjectModel namespace.

SLaks
array was just an exmaple. I am thinking about some Collection.Didn't know about ReadOnlyCollection. Thx!
lukas
+4  A: 

Automatic properties have no bearing on this - the same options are available for automatic properties and "manual" properties. You can restrict the access of the setter like this:

// Setter access only to this type and nested types
public string Name { get; private set; }
// Setter access within the assembly
public Group[] Groups { get; internal set; }

etc

... but you can't do it for a single class (unless that class is nested within the declaring type, in which case private would be fine). There's no namespace-restricted access in .NET or C#.

(It's not entirely clear which class the properties are declared in - if they're TdmReader properties, then just make them private. If they're TdmFile properties, you have the problem described above.)

Jon Skeet
"// Setter access only to this type and nested typespublic string Name { get; private set; }"AFIR, nested Class in C# has no reference to outer Class ( like in Java) it must be passed via contructor f.e.with "manual: property i could co C-style trick set{ if(sth != null) { //some msg or ex} else { sth = value }}
lukas