The best way to do this is by creating a 'ColorValue' class.
something like this
It's deemed good practice wrap a primitive type like this when you would use it as a 'type' in your program and only use primitive types like int, string etc within methods for calculations (within a small scope and not public throughout your app).
You may also need to write ToString() and other interface methods etc as needed.
Thanks Mike!
Was looking exactly how it should be done.. since
int is a non-nullable type, the compiler throws error if I try to set the
int property to null.
Maybe instead of throwing an exception when the value is out of range, perhaps in this case would be more appropriate to return a negative int value?
Although the best behaviour would be to
"throw an exception at runtime", like you mentioned in your next post.
BTW your example works fine even if it was defined as
struct instead of
class.
Could you just define the properties as byte ( Unsigned 8-bit integer ) ?
Thanks kdub,
byte worked perfectly for this case -
struct TrueColor
{
public byte Red;
public byte Green;
public byte Blue;
}
Could you just define the properties as byte ( Unsigned 8-bit integer ) ?
good point, would that truncate the value on both sides or throw an exception at runtime? For example, if a user enters a larger value at a prompt?
Would be nice if there was a runtime validation, upon a custom criteria - like in your example from reply #1.
Although even if it was possible, the compiler would be able to validate it only on a constant variable (because the value would be predefined) and not on an user input like
Console.ReadLine();My question started upon exploring
structs more carefuly, before I was just using classes with properties and constructors.
But realised that instead of defining 5-6 Constructors to validate (all or some of) the properties, I could just use a
struct, so I remembered John's
cowThe problem was I didn't knew how to validate within the property (without a constructor).. in order to apply a range to the cow's weight.
But now I know, thanks to Mike's replly!
I was attempting to solve this exercise #12
from here, where the validation steps into the next level (having an unique ID for every employee)
12. A company dealing with marketing wants to keep a data record of its employees.
Each record should have the following characteristic – first name, last name, age, gender (‘m’ or ‘f’) and unique employee number (27560000 to 27569999).
Declare appropriate variables needed to maintain the information for an employee by using the appropriate data types and attribute names.
So I guess that would mean wrapping the Employee struct within a Employess class, along with a List<Employee> to iterate through due the ID validation ?
(BTW I'm not changing my question, I'm expanding it)