How to make a structure (struct) in C#?

Asked

Viewed 597 times

3

How to make a C# structure in which you create a type?

For example, in C++ we use:

struct teste
{
  int a;
  char c[30];
};

2 answers

5


First it would be good to have a read in that question to understand how the struct in C#, it’s not quite the same as in C or C++. Although it doesn’t differ much.

So in this case you can do something similar:

unsafe struct teste {
    public int a;
    public fixed char c[30];
};

You can only reproduce the same effect with unsafe. This structure will be 34 bytes in size (in 32-bit code), as expected. But in fact it should not do identical. First code unsafe only to be used when there is real need and no substitute, and this form is not idiomatic. Second, something so great should be a class. This can be better understood in link above. The most idiomatic form would be so:

struct Teste {
    public int a;
    public byte[] c;
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that members are explicitly public. This is a requirement of C#. The syntax of array is a little different and does not allow setting a size limit that can be used. To get more expensive of C# I changed the name to use capital which is normal in the language and removed the ; End that is unnecessary. Could still have created a constructor that would facilitate the initialization of the structure and even create a size barrier:

struct Teste {
    public int a;
    public char[] c;
    public Teste(int size = 30) {
        if (size > 30) {
            throw new ArgumentException($"parâmetro deve ter tamanho máximo de 30");
        }
        a = 0;
        c = new char[size];
    }
    public Teste(int a, char[] c) {
        if (c.Length > 30) throw new ArgumentException($"parâmetro para {nameof(c)} deve ter tamanho máximo de 30");
        this.a = a;
        this.c = c;
    }
    public Teste(int a, string c) : this(a, c.ToCharArray()) {}
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that this shape is a little different. A struct has 8 bytes size (in code 32 bits), plus one array of until 30 characters (60 bytes plus the cost of allocating the object and other properties of the array, as its size, for example, is after all a separate object and the char standard C# has 2 bytes to work well with UTF, and in fact each character can occupy more than one position, although rare) that will always be in the heap.

Remember that struct is not used by reference, so it will always be allocated to stack or within another object in the heap. There is a different semantics there. If you need semantics by reference, use a class (you can also use a parameter ref in some cases). In C# this has a clear distinction according to the link of the question at the beginning of the answer.

Obviously there’s an error in the last attempt as expected.

This form is no longer compatible with a struct of C/C++, although it is compatible with some/a lot of effort on the side of these languages.

As last optimization I would change the array of char for string, a better type for this in C#, I wouldn’t worry too much about the size and turn into a structure immutable, which is correct for a struct in C#, using properties instead of public fields and with better names:

struct Teste {
    public int Numero {get;}
    public string Texto {get;}
    public Teste(int numero, string texto) {
        Numero = numero;
        Texto = texto;
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Now it looks C# in the best shape.

3

Same thing as your example, only without the ; at the end. Follow the example:

public struct Livro
{
   public decimal Preco;
   public string Titulo;
   public string Autor;
}

For more information, check out this link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.