[Design] return char[] or string?

Regan Heath regan at netmail.co.nz
Thu Aug 23 01:18:10 PDT 2007


Manfred Nowak wrote:
> Regan Heath wrote
> 
>> Yeah, this is another of those cases where a property doesn't
>> quite work the same as a plain old data member, p.property += x;
>> being the more common one.
> 
> Again I do not see the deeper reason for a whole discussion. This time 
> this discussion about properties. Properties _are_ restricted. If one 
> do not want this restrictions, one can use a class instead.

http://www.digitalmars.com/d/property.html
"Properties are member functions that can be syntactically treated as if 
they were fields"

I was under the impression the main benefit to properties was being able 
to replace an existing field (one in use by some user code) with a 
property and have it work without user code changes.

eg.

---------BEFORE--------

class A
{
   public int a;
}

void foo(ref int i) {}

void main()
{
	A a = new A();
         int b;

         b = a.a = 5;
	a.a += 1;
	a.a++;
	foo(a.a);
}

---------AFTER---------

<after>
class A
{
   int _a;
   public int a() { return _a; }
   public int a(int _aa) { _a = _aa; return a(); }
}

void main()
{
	A a = new A();
         int b;

         b = a.a = 5;  //error
	a.a += 1;     //error
	a.a++;        //error
         foo(a.a);     //error
}

Sadly there are plenty of cases where a property cannot be 
"syntactically treated as a field" but needs a completely different syntax.

Sure, there are other benefits for properties like performing some 
complex calculation on the input to the setter, or error checking it, or 
whatever but I don't think this is the core benefit to properties as 
these can be achieved with plain old methods i.e. set<Propertyname>

Something that would solve 3 of the errors above is the ability to 
return by 'ref', eg.

class A
{
   int _a;
   public ref int a() { return _a; }
   public ref int a(int _aa) { _a = _aa; return a(); }
}

void main()
{
	A a = new A();
         int b;

         b = a.a = 5;  //error
	a.a += 1;     //ok
	a.a++;        //ok
         foo(a.a);     //ok
}

The problem with the remaining error is that a setter might take and 
return 2 different types, as mentioned here:
   http://www.digitalmars.com/d/archives/digitalmars/D/10199.html

Regan


More information about the Digitalmars-d-learn mailing list