Property Default Value

S

shapper

Hello,

I have a class with two properties:

public String DefaultCulture { get; set; }
public String Cultures { get; set; }

What is the correct way to define a default value for each one if they
are not defined?

Thanks,
Miguel
 
S

Scott M.

In the class constructor, you can set the values to whatever you need. But,
since you won't have a property backing field using this syntax, you'll have
to set the default value directly on the property.

-Scott
 
P

Peter Duniho

shapper said:
Hello,

I have a class with two properties:

public String DefaultCulture { get; set; }
public String Cultures { get; set; }

What is the correct way to define a default value for each one if they
are not defined?

You should be more specific. For one, the value of each property _is_
always defined. If you don't initialize it, it's initialized to null
for you.

There is the [DefaultValue] attribute, which you can use to indicate to
the VS Designer what the default value for the property should be. But
that's used only by the Designer; you still need to implement the
default value in your own code.

If you want to have the concept of a property that is as-yet unassigned,
you cannot do that with automatic properties. That's because to track
assignment of the property would require an explicit implementation of
the setter, and to return something other than the currently assigned
value of the property would require an explicit implementation of the
getter.

If the above doesn't answer your question, you should clarify the question.

Pete
 
A

Arne Vajhøj

I have a class with two properties:

public String DefaultCulture { get; set; }
public String Cultures { get; set; }

What is the correct way to define a default value for each one if they
are not defined?

Default values should be set in the constructor, when you are
using automatic properties.

I would most likely prefer to use:

public CultureInfo DefaultCulture { get; set; }
public CultureInfo Culture { get; set; }

Arne
 

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

Similar Threads

Maybe Partial? 9
Property Default Values in C# 5
Wire a Configuration to a Service 4
Intersection of Lists 5
Override property 18
Interface in Property 4
Property 7
Generate Property 3

Top