Re: struct

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Mohammad wrote:
14 7/8" x 8 1/2" wrote:

I want to use a struct to constrain a result.

The result is a string composed of several strings of fixed length;

Result is composed of 3 strings, each 4 char in length.

Can I build a struct that would enforce such a construct?

Yes you can, something like the following:

struct MyResult
{
    private string s1 = string.Empty;
    private string s2 = string.Empty;
    private string s3 = string.Empty;

I tried doing this and VS.NET reports:

"cannot have instance field initializers in structs"




public string S1 { get { return s1; }

        set
        {
            if ( value.Length <= 3 )
                s1 = value;
            else
                throw new InvalidOperationExcpetion();
        }
    }

    // repeat for S2 and S3

}

.