Automatically generating get and set properites for private class data

  • Thread starter Thread starter Charles
  • Start date Start date
C

Charles

How often have you seen this kind a of construct in a .NET class:

class A
{
private string b;
public string B
{
get { return b; }
set { b = value; }
}
}

Wouldn't it be nice to have an attribute you could place on the member
data that would automatically generate the corresponding properties?
It would look something like this:

class A
{
[Property(name="B", get=true, set=true)]
private string b;
}

Has anyone see something similar to this? There seems to be no way to
write a custom attribute that generates code at compile time, but
perhaps there's another way to accomplish such a thing?

Charles
 
Wouldn't it be nice to have an attribute you could place on the member
data that would automatically generate the corresponding properties?

Not as an attribute, IMO - I'd rather have it as a new keyword (or a
context-sensitive keyword to avoid conflicts).

I'm not terribly keen on attributes affecting compile-time behaviour,
beyond conditional ones...

Jon
 
This is going to be in C# 3.0. The syntax will be:

public string MyProperty
{
get;
set;
}

This will auto-magically create the backing field for you. You won't be
able to acess this field, since you won't know what the name of it will be.
Because of this, you should NOT use this language feature if you are going
to adorn the class with a Serializable attribute (the DataContract attribute
is ok, but if you need to have that field stored when the structure is read,
then you will have to go back to the old way).
 
Nicholas Paldino said:
This is going to be in C# 3.0. The syntax will be:

public string MyProperty
{
get;
set;
}

This will auto-magically create the backing field for you. You won't be
able to acess this field, since you won't know what the name of it will be.
Because of this, you should NOT use this language feature if you are going
to adorn the class with a Serializable attribute (the DataContract attribute
is ok, but if you need to have that field stored when the structure is read,
then you will have to go back to the old way).

Hooray - I've been after the field-hiding aspect for ages :)

I don't remember seeing that on my last skim through the C# 3 spec - I
dare say it's out of date :(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top