Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform struct inline initialization in C#?

What member should I implement in my arbitrary structure to make the following assignment possible:

public struct MyStruct {    String s;    Int length; }  MyStruct myStruct = new MyStruct { s = "Hello", length = 5 };  // Now, I want the following code to set the 's' to "Lol" and the // length to 3 (length of "Lol"). The second part should be done // automatically. myStruct = "Lol"; // Or myStruct = String("Lol"); 

How should this be done?

like image 414
Yippie-Ki-Yay Avatar asked Dec 12 '10 02:12

Yippie-Ki-Yay


People also ask

How do you initialize a struct in C?

Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.

How do you initialize a structure?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can you initialize values in a struct?

No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).

Can we initialize variable in structure in C?

Structure members cannot be initialized with declaration.


2 Answers

You use an implicit operator that converts the string value to a struct value:

public struct MyStruct {   public string s;   public int length;    public static implicit operator MyStruct(string value) {     return new MyStruct() { s = value, length = value.Length };   }  } 

Example:

MyStruct myStruct = "Lol"; Console.WriteLine(myStruct.s); Console.WriteLine(myStruct.length); 

Output:

Lol 3 
like image 133
Guffa Avatar answered Oct 08 '22 23:10

Guffa


Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

like image 31
supercat Avatar answered Oct 09 '22 00:10

supercat