Code Red > .NET

How to validate a property of a struct ?

(1/4) > >>

Grrr1337:
Hey .NET guys, I have a simple question and can't seem to find a simple anwer..
Is there a way to validate the property value of a struct ?

Example:

--- Code - C#: ---class Program{    void test()    {        TrueColor MyColor;        MyColor.Red = 212;        MyColor.Green = 152;        MyColor.Blue = 314; // <- invalid asignment    }} struct TrueColor{ // can these properties be in the range of 0-255 ?    public int Red;    public int Green;    public int Blue;}

MickD:
The best way to do this is by creating a 'ColorValue' class.

something like this

--- Code - C#: ---class ColorValue{    private int _value;     public int Value{        get {            return _value;        }        set {            if (value > 255){                // cap it and continue (or throw exception?):                _value = 255;            }            else if (value < 0){                _value = 0;            } else {                _value = value;            }        }    }} 
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.

kdub_nz:
Could you just define the properties as byte ( Unsigned 8-bit integer ) ?

MickD:

--- Quote from: kdub on January 05, 2019, 08:04:11 PM ---Could you just define the properties as byte ( Unsigned 8-bit integer ) ?

--- End quote ---

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?

kdub_nz:
If it's a user prompt I'd use
--- Code - C#: ---byte.tryParse()

Navigation

[0] Message Index

[#] Next page

Go to full version