Automatic properties

  • Thread starter Thread starter Peter K
  • Start date Start date
P

Peter K

Hi

is it possible to have a default value for an automatic property?

For example, say I have a property

public string Name { get; set; }

Can I have the "name" set to a default value of "Peter"? (I guess I could
write a constructor that does this).


/Peter
 
Hi Peter,

Properties do indeed have a possible default value and a default value is
not bolded if you set a property to its default value in the designer.

[DefaultValue("Peter")]
public string MyProperty
{
get;
set;
}
 
Peter K said:
is it possible to have a default value for an automatic property?

No, unfortunately not.
For example, say I have a property

public string Name { get; set; }

Can I have the "name" set to a default value of "Peter"? (I guess I could
write a constructor that does this).

Yup, that's the option.

The other restriction is that you can't have a readonly automatic
property. I'd like to be able to write:

public readonly string Name { get; }

or maybe

public string Name { get; readonly set; }

which would allow the setter to be used only within the constructor,
and the autogenerated variable to be marked as readonly.
 
Morten Wennevik said:
Properties do indeed have a possible default value and a default value is
not bolded if you set a property to its default value in the designer.

[DefaultValue("Peter")]
public string MyProperty
{
get;
set;
}

That may work when using designers etc, but it's not going to help
outside that scenario. For instance:

using System;
using System.ComponentModel;

class Test
{
[DefaultValue("Peter")]
public string Name
{
get;
set;
}

static void Main()
{
Test t = new Test();
Console.WriteLine(t.Name);
}
}

That won't write "Peter".
 

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