26.1 First look at structs


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]

[3] In this example, public accessor and mutator methods are used to access the private fields. Structs can also contain public properties instead.

Like classes:

  • structs can contain both function members [4] and data members [5] “ they can be static or non-static;

    [4] Function members are indexers, constructors, operators, properties, and any method. There is one exception here “ a struct cannot have a destructor.

    [5] Data members are read-only variables , constants, events, and fields.

  • structs can be declared with the following accessibility modifiers “ public , protected , internal , and private with the same effect as classes;

  • structs can be hidden using the new modifier;

  • structs can implement one or more interfaces (though they cannot extend another class or another struct) “ to make the Name struct implement the MyInterface interface, just declare the struct like this:

     struct Name:MyInterface{     ... } 


From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net