Back to notes -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'        Slide program -- Keyboard shortcut: 't'    An extended demonstration of structs in C#.Lecture 2 - slide 12 : 43
Program 3
/* Right, Wrong */   

using System;

public struct Point1 {  
  public double x, y;
}   

public struct Point2 {  
  public double x, y;   
  public Point2(double x, double y){this.x = x; this.y = y;}  
  public void Mirror(){x = -x; y = -y;}                       
}   

public class StructDemo{

 public static void Main(){

   /*   
   Point1 p1;  
   Console.WriteLine(p1.x, p1.y);   
   */
   
   Point1 p2;  
   p2.x = 1.0; p2.y = 2.0;    
   Console.WriteLine("Point is: ({0},{1})", p2.x, p2.y);   

   Point1 p3;
   p3 = p2;                    
   Console.WriteLine("Point is: ({0},{1})", p3.x, p3.y);   
   
   Point2 p4 = new Point2(3.0, 4.0);   
                                       

   p4.Mirror();                        
   Console.WriteLine("Point is: ({0},{1})", p4.x, p4.y);   
 }

}
An extended example. Green: OK.  Red: Errors.
 
 
 
A simple struct Point1 - only with fields.
 
 
 
An extended struct Point2 - with fields
 
constructor, and
a method.
 
 
 
 
 
 
 
 
Illegal:  p1.x and p2.y are not initialized
 
 
 
The fields of point p2 are now initialized 
 
 
 
The point p2 is copied (field by field) to Point p3 
 
 
Point p4 of type Point2 is 
initialized via the constructor
 
An operation, Mirror, is called on p4
(-3.0, -4.0)