First, there is no way to transpose the semantics from C to C#. Nothing you do will be the same. There are several differences, even if it seems to be the same thing.
There is no way to initialize members of a structure directly, it has to:
- be in a builder
- initialize with a value passed to the constructor (cannot be the default constructor)
- initialize all members.
That would work:
public class Program {
public static void Main() {
var nome = new Name(new char[32]);
}
}
public struct Name {
public Name(char[] nome) => Nome = nome;
public char[] Nome;
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
If you want you can do a validation to ensure that the size has 32 characters. But as I said will never be equal to C. It would also be interesting to check if came reasonable data. A structure should never be in invalid state. A class too, but in structures is much more important.
One way to bring semantics a little closer is to use a fixed
, as shown in another question.
It is possible to give other solutions, but without context it is difficult to say something. To tell the truth the example shows that something very wrong is being done.
Some people do something like this (I do not like for various reasons, for me it is Ambi the thick and bad for performance and memory consumption)
public class Program {
public static void Main() {
var nome = new Name();
}
}
public struct Name {
private bool inicializado;
private char[] nome;
public char[] Nome { get {
if (!inicializado) {
nome = new char[32];
inicializado = true;
}
return nome;
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
One possibility is to create a property that initializes (C# 6 up), but only if you have only this member, if you have two members it no longer works. The above example works.
In C# it is necessary to be very careful with the creation of structures. In C too, but in C it is true for anything. Structure has peculiarities that many programmers do not understand.
One of them is that this structure will have its size of 4 or 8 bytes depending on the architecture and you never need to check it. Like I said, it’s not like C.
This structure in the way it is is completely unnecessary in C# and C as well.
I’ve improved the style, but there’s still some really weird stuff in the code.
public char[] nome;
– Jéf Bueno
@LINQ Not initializing a size doesn’t work for me, because I need to get the struct sizeof later.
– Francisco
Why do you need the struct?
– ramaral
@ramaral To read a process string.
– Francisco
If you know what "encoding" used just convert
byte[]
for string.– ramaral