[edit] Define a struct in csharp
Structs are nothing but a custom variable. Structs are composed of several pieces that make the struct up. Suppose that you want to create a struct that defines a customer. These are the pieces that will compose of the struct: Name, age, sex, birthday, join date, etc. All of this information can be placed in the struct.
struct <StructName>
{
<declare members here>
}
Example:
using System;
class Program
{
struct customer
{
public string name;
public int age;
public char sex;
}
static void Main(string[] args)
{
customer x;
x.name = "john";
x.age = 18;
x.sex = 'm';
Console.WriteLine("Customer Info");
Console.WriteLine("Name: " + x.name);
Console.WriteLine("Age: " + x.age);
Console.WriteLine("Sex: " + x.sex);
Console.Read();
}
}
Output:
Customer Info
Name: john
Age: 18
Sex: m
- public keyword is used so you can access the variables from the main block. Always use keyword public
- You can also declare multiple structs in the same program
- Use the . operator to access and assign parts of the struct
|