You will be surprised how much structs appear to be like classes at first sight. A struct is declared in the code below to represent a person's name . This is done using the struct keyword. 1: using System; 2: 3: struct Name { 4: private string FirstName; 5: private string LastName; 6: 7: public string GetName(){ 8: return FirstName + " " + LastName; 9: } 10: 11: // accessors and mutators 12: public string GetFirstName(){ 13: return FirstName; 14: } 15: public void SetFirstName(string newFirstName){ 16: FirstName = newFirstName; 17: } 18: public string GetLastName(){ 19: return LastName; 20: } 21: public void SetLastName(string newLastName){ 22: LastName = newLastName; 23: } 24: } That's the Name struct. Now you can instantiate and use it. 25: class TestClass{ 26: public static void Main(){ 27: Name n = new Name(); 28: n.SetFirstName("Charlie"); 29: n.SetLastName("Brown"); 30: Console.WriteLine(n.GetName()); 31: } 32: } Output: c:\expt>test Charlie Brown On line 27, a new instance of the Name struct is created. On lines 28 “ 30 its methods are invoked. [3]
Like classes:
|