struct

  • Thread starter Thread starter 14 7/8\ x 8 1/2\
  • Start date Start date
1

14 7/8\ x 8 1/2\

I want to use a struct to constrain a result.

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

Let's say the string

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

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

I tried putting string[] s = new string[4] in my struct but it wouldn't
let me.
 
14 said:
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;

public string S1
{
get
{
return s1;
}

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

// repeat for S2 and S3

}
 
excellent!

and then i should be able to add in the struct:

public string sAll
{
get
{
return s1 + s2 + s3;
}
}
 
Mohammad said:
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"
 
Hi Marv,

instance fields in structs cannot be initiated with value.

Just remove the "= string.Empty;" parts and it will work.

Hope it helps,
Neno
 
Be aware that if you use a struct, all strings will be by default
initialized to null. There is nothing you can do about that. So, you
must put checks in your code for null strings, as this is a very real
possibility. So, your code for sAll should read:

public string sAll
{
get
{
string all = "";
if (s1 != null)
{
all += s1;
}
if (s2 != null)
{
all += s2;
}
if (s3 != null)
{
all += s3;
}
return all;
}
}

By the way, is there any particular reason you're using a struct and
not a class? A class wouldn't have this problem....
 
Bruce Wood said:
Be aware that if you use a struct, all strings will be by default
initialized to null. There is nothing you can do about that. So, you
must put checks in your code for null strings, as this is a very real
possibility. So, your code for sAll should read:

public string sAll
{
get
{
string all = "";
if (s1 != null)
{
all += s1;
}
if (s2 != null)
{
all += s2;
}
if (s3 != null)
{
all += s3;
}
return all;
}
}

There's no need for that, as a null in string concatenation comes out
as an empty string anyway. The above is semantically equivalent to (but
less efficient than)

return s1+s2+s3;
 
Back
Top