miércoles, noviembre 03, 2004

Accessor Modifiers in CVS

The code for accessor modifiers support is -finally- in CVS. I wanted it to e included in the last release that will be taken place tomorrow (the development release, of course). However, as I said before, it is now in CVS in the mcs module.

The accessor modifiers are a new feature part of the C# 2.0 specification, and with it now is possible to add an access modifier -such PUBLIC, PRIVATE, etc- for the accessors -get/set- in the properties.

This is something important in classes where you want to keep some data hidden, and want to have your Property read-only, for example. A very common behavior for a class would be to have, then, your get accessor public, and keep your set accessor protected:


public int Count {
get {
// count is a private int field
return count;
}
protected set {
// Only protected members will be able to modify Count
count = value;
}
}


With accessor modifiers, there is improvement hiding get or set methods defined by a Property, thus avoiding the need no keep a lot of variables protected.

The rules for applying this are: your access modifier must be more restrictive than the parent, when overriding the accessor must keep the parent access modifier, and that if yor property has only a an accessor (only set or only get) you can't define an access modifier.

With the first, that implies every access modifier must be more restrictive than the parent, it is not possible to have:


public int Count {
get {
}
//
// Error: public is not more restrictive than public
//
public set {
}
}


The second is very obvious, but the third says you can't have a property just only one a accessor that has access modifier:


public int Count {
//
// Error: Property must have both set and get accessors
// for applying access modifiers
//
protected get {
}
}


And finally, a sample:

using System;

public class Test {
string message;

public Test (string message)
{
this.message = message;
}
public string Message {
get {
return message;
}
protected set {
message = value;
}
}

static void Main ()
{
Test t = new Test ("Mono");

// Good, it is possible to access get accessor
Console.WriteLine (t.Message);

// Bad, mcs will complain about the access
// t.Message = "Hey";
}
}

3 comentarios:

Roberto Iza Valdés dijo...
Este blog ha sido eliminado por un administrador de blog.
Roberto Iza Valdés dijo...
Este blog ha sido eliminado por un administrador de blog.
Unknown dijo...
Este comentario ha sido eliminado por el autor.