propery declarations with fixed choices

  • Thread starter Thread starter John Slate
  • Start date Start date
J

John Slate

I need to design a reusable component with several settable properties.
For some of these properties, there will need to be choices that have
fixed values. What is the best way to go about this? Examples would be
great!
 
John,

Basically, I would create an enumeration, and then expose your property
as that.

For example, say you have a property that is for the days of the week
(there is a DayOfWeek enumeration in the framework). You would define your
property as:

// The value.
private DayOfWeek dayOfWeek = DayOfWeek.Sunday;

public DayOfWeek Day
{
get
{
return dayOfWeek;
}
set
{
// Check to see that the value is valid. If it is not, then throw
// an exception.
if (!Enum.IsDefined(typeof(DayOfWeek), value))
{
// Throw an exception.
// This could be OutOfRangeException, or anything you feel is
appropriate.
throw new InvalidArgumentException();
}

// Set the value.
dayOfWeek = value;
}
}

Hope this helps.
 
John Slate said:
I need to design a reusable component with several settable properties.
For some of these properties, there will need to be choices that have
fixed values. What is the best way to go about this? Examples would be
great!

Enumerations are the usual way of giving multiple choice. If that isn't
appropriate, you can always do checking in the "setter" and throw an
exception if the value the client is trying to set the property to is
invalid.
 
I guess that a better way of asking this question is also ask how can I
get this list of choices into Intellisense, so that another developer
using the component will only have fixed choices? Thanks...
 
John,

If you make the property an enumeration, then it will show up in
Intellisense.

However, that doesn't mean that the developer can't force some other
value into the property (which is what the check in the set part of the
property is for).
 
Back
Top