private struct Strings {
public string s1;
public string s2;
}
Strings myStrings = new Strings();
Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly. However, doing something like int size = myStrings.s1.Length throws a NullReferenceException. I don't understand why myStrings.s1 does not exist. Aren't s1 and s2 created automatically when I create a new object called myStrings??
Hello anonim:
> Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly.
I'm afraid this is not correct. There's no implicit initialization of objects anywhere and your strings won't be created automatically.
So here is how one commonly would write it:
private struct Strings {
public string s1;
public string s2;
public Strings() {
s1 = String.Empty;
s2 = String.Empty;
}
}
Strings myStrings = new Strings();
Feel free to ask more.
HTH. -LV
Ludovico, thanks for your reply.
Per the MSDN [link]:
"Unlike a class, a struct is not permitted to declare a parameterlessinstance constructor. Instead, every struct implicitly has aparameterless instance constructor that always returns the value thatresults from setting all value type fields to their default value andall reference type fields to null. A struct can declare instance constructors having parameters."
So based on that, you cannot create a parameterless constructor for any struct (public Strings() { ...} does not compile - try it).
The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct? So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.
Thanks for your help.
anonim:
> Unlike a class, a struct is not permitted to declare a parameterless instance constructor.
Yes, you are right, sorry...
> The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct?
Yes: String is a class, so strings are reference types, not value types.
> So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.
Right again!
Cheers. :) -LV
Thank you much!
0 comments:
Post a Comment