A struct uses syntax similar to a class. It is a type definition. A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:
Example:-
Output:- MS
Note:-
Conclusion:
Means that struct stores its data in its type. It is not allocated separately on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.
Example:-
using System; class Program { public struct Book { public decimal price; public string title; public string author; public bool IsAvailable; }; static void Main() { // ... Create struct on stack. Book B; B.price = 100.00; B.title = "MS"; B.author = "Vepsh"; B.IsAvailable=true; // ... Write struct field. Console.WriteLine(B.title); } }
Output:- MS
Note:-
- Please notice how, in Main, the struct is created on the stack. No "new" keyword is used. It is used like a value type such as int.
- Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
- Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
Conclusion:
Means that struct stores its data in its type. It is not allocated separately on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.
No comments:
Post a Comment