Base Class Reference Can Refer To Derived Class Object – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// A base class reference can refer to a derived class object. using System; class X { public int a; public X(int i) { a = i; } } class Y : X { public int b; public Y(int i, int j) : base(j) { b = i; } } public class BaseRef { public static void Main() { X x = new X(10); X x2; Y y = new Y(5, 6); x2 = x; // OK, both of same type Console.WriteLine("x2.a: " + x2.a); x2 = y; // still Ok because Y is derived from X Console.WriteLine("x2.a: " + x2.a); // X references know only about X members x2.a = 19; // OK // x2.b = 27; // Error, X doesn't have a b member } }
Abstract Classes And Methods – Class Interface
using System;abstract public class MotorVehicle { public string make; public string model; public MotorVehicle(string make, string model) { this.make = make; this.model = model; } abstract public void Accelerate();}public class Product : MotorVehicle { public Product(string make, string model) : base(make, model) { // do nothing } public override void Accelerate() { Console.WriteLine("In Product Accelerate() method"); Console.WriteLine(model + " accelerating"); } }class MainClass { public static void Main() { Product myProduct = new Product("Toyota", "MR2"); myProduct.Accelerate(); } }
Access To Private Field Through Property – Class Interface
/* C# Programming Tips & Techniques by Charles Wright, Kris JamsaPublisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // Property.cs -- Demonstrates access to a private field through a property. // Compile this program with the following command line: // C:>csc Property.cs // namespace nsProperty { using System; public class Property { const double radian = 57.29578; const double pi = 3.14159; int Angle { get { int angle = (int) (fAngle * radian + 0.5); angle = angle == 360 ? 0 : angle; return (angle); } set { double angle = (double) value / radian; if (angle < (2 * pi)) { fAngle = angle; Console.WriteLine ("fAngle set to {0,0:F5}", fAngle); } else { Console.WriteLine ("fAngle not modified"); } } } double fAngle = 0.0; // Angle in radians static public int Main (string [] args) { int angle; try { angle = int.Parse (args[0]); } catch (IndexOutOfRangeException) { Console.WriteLine ("usage: circle [angle in degrees]"); return (-1); } catch (FormatException) { Console.WriteLine ("Please use a number value for the angle in degrees"); return (-1); } Property main = new Property(); main.Angle = angle; Console.WriteLine ("The angle is {0} degrees", main.Angle); return (0); } } }
Add Constructor To Building – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add a constructor to Building. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants public Building(int f, int a, int o) { floors = f; area = a; occupants = o; } // Display the area per person. public int areaPerPerson() { return area / occupants; } /* Return the maximum number of occupants if each is to have at least the specified minum area. */ public int maxOccupant(int minArea) { return area / minArea; } } // Use the parameterized Building constructor. public class BuildingDemo21 { public static void Main() { Building house = new Building(2, 2500, 4); Building office = new Building(3, 4200, 25); Console.WriteLine("Maximum occupants for house if each has " + 300 + " square feet: " + house.maxOccupant(300)); Console.WriteLine("Maximum occupants for office if each has " + 300 + " square feet: " + office.maxOccupant(300)); } }
Add Constructor To Triangle – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// Add a constructor to Triangle. using System; // A class for two-dimensional objects. class TwoDShape { double pri_width; // private double pri_height; // private // properties for width and height. public double width { get { return pri_width; } set { pri_width = value; } } public double height { get { return pri_height; } set { pri_height = value; } } public void showDim() { Console.WriteLine("Width and height are " + width + " and " + height); } } // A derived class of TwoDShape for triangles. class Triangle : TwoDShape { string style; // private // Constructor public Triangle(string s, double w, double h) { width = w; // init the base class height = h; // init the base class style = s; // init the derived class } // Return area of triangle. public double area() { return width * height / 2; } // Display a triangle's style. public void showStyle() { Console.WriteLine("Triangle is " + style); } } public class Shapes3 { public static void Main() { Triangle t1 = new Triangle("isosceles", 4.0, 4.0); Triangle t2 = new Triangle("right", 8.0, 12.0); Console.WriteLine("Info for t1: "); t1.showStyle(); t1.showDim(); Console.WriteLine("Area is " + t1.area()); Console.WriteLine(); Console.WriteLine("Info for t2: "); t2.showStyle(); t2.showDim(); Console.WriteLine("Area is " + t2.area()); } }
Add Method That Takes Two Arguments – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add a method that takes two arguments. using System; class ChkNum { // Return true if x is prime. public bool isPrime(int x) { for(int i=2; i < x/2 + 1; i++) if((x %i) == 0) return false; return true; } // Return the least common denominator. public int lcd(int a, int b) { int max; if(isPrime(a) | isPrime(b)) return 1; max = a < b ? a : b; for(int i=2; i < max/2 + 1; i++) if(((a%i) == 0) & ((b%i) == 0)) return i; return 1; } } public class ParmDemo1 { public static void Main() { ChkNum ob = new ChkNum(); int a, b; for(int i=1; i < 10; i++) if(ob.isPrime(i)) Console.WriteLine(i + " is prime."); else Console.WriteLine(i + " is not prime."); a = 7; b = 8; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); a = 100; b = 8; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); a = 100; b = 75; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); } }
Add Method To Building – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add a method to Building. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants // Display the area per person. public void areaPerPerson() { Console.WriteLine(" " + area / occupants + " area per person"); } } // Use the areaPerPerson() method. public class BuildingDemo2 { public static void Main() { Building house = new Building(); Building office = new Building(); // assign values to fields in house house.occupants = 4; house.area = 2500; house.floors = 2; // assign values to fields in office office.occupants = 25; office.area = 4200; office.floors = 3; Console.WriteLine("house has:\n " + house.floors + " floors\n " + house.occupants + " occupants\n " + house.area + " total area"); house.areaPerPerson(); Console.WriteLine(); Console.WriteLine("office has:\n " + office.floors + " floors\n " + office.occupants + " occupants\n " + office.area + " total area"); office.areaPerPerson(); } }
Add Indexer In Interface – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add an indexer in an interface. using System; public interface ISeries { // an interface property int next { get; // return the next number in series set; // set next number } // an interface indexer int this[int index] { get; // return the specified number in series } } // Implement ISeries. class ByTwos : ISeries { int val; public ByTwos() { val = 0; } // get or set value using a property public int next { get { val += 2; return val; } set { val = value; } } // get a value using an index public int this[int index] { get { val = 0; for(int i=0; i<index; i++) val += 2; return val; } } } // Demonstrate an interface indexer. public class SeriesDemo4 { public static void Main() { ByTwos ob = new ByTwos(); // access series through a property for(int i=0; i < 5; i++) Console.WriteLine("Next value is " + ob.next); Console.WriteLine("\nStarting at 21"); ob.next = 21; for(int i=0; i < 5; i++) Console.WriteLine("Next value is " + ob.next); Console.WriteLine("\nResetting to 0"); ob.next = 0; // access series through an indexer for(int i=0; i < 5; i++) Console.WriteLine("Next value is " + ob[i]); } }
Add Constructors To Twodshape – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// Add constructors to TwoDShape. using System; // A class for two-dimensional objects. class TwoDShape { double pri_width; // private double pri_height; // private // Constructor for TwoDShape. public TwoDShape(double w, double h) { width = w; height = h; } // properties for width and height. public double width { get { return pri_width; } set { pri_width = value; } } public double height { get { return pri_height; } set { pri_height = value; } } public void showDim() { Console.WriteLine("Width and height are " + width + " and " + height); } } // A derived class of TwoDShape for triangles. class Triangle : TwoDShape { string style; // private // Call the base class constructor. public Triangle(string s, double w, double h) : base(w, h) { style = s; } // Return area of triangle. public double area() { return width * height / 2; } // Display a triangle's style. public void showStyle() { Console.WriteLine("Triangle is " + style); } } public class Shapes4 { public static void Main() { Triangle t1 = new Triangle("isosceles", 4.0, 4.0); Triangle t2 = new Triangle("right", 8.0, 12.0); Console.WriteLine("Info for t1: "); t1.showStyle(); t1.showDim(); Console.WriteLine("Area is " + t1.area()); Console.WriteLine(); Console.WriteLine("Info for t2: "); t2.showStyle(); t2.showDim(); Console.WriteLine("Area is " + t2.area()); } }
Add Length Property To Failsoftarray – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// Add Length property to FailSoftArray. using System; class FailSoftArray { int[] a; // reference to underlying array int len; // length of array -- underlies Length property public bool errflag; // indicates outcome of last operation // Construct array given its size. public FailSoftArray(int size) { a = new int[size]; len = size; } // Read-only Length property. public int Length { get { return len; } } // This is the indexer for FailSoftArray. public int this[int index] { // This is the get accessor. get { if(ok(index)) { errflag = false; return a[index]; } else { errflag = true; return 0; } } // This is the set accessor set { if(ok(index)) { a[index] = value; errflag = false; } else errflag = true; } } // Return true if index is within bounds. private bool ok(int index) { if(index >= 0 & index < Length) return true; return false; } } // Demonstrate the improved fail-soft array. public class ImprovedFSDemo { public static void Main() { FailSoftArray fs = new FailSoftArray(5); int x; // can read Length for(int i=0; i < fs.Length; i++) fs[i] = i*10; for(int i=0; i < fs.Length; i++) { x = fs[i]; if(x != -1) Console.Write(x + " "); } Console.WriteLine(); // fs.Length = 10; // Error, illegal! } }
Add More Constructors To Twodshape – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// Add more constructors to TwoDShape. using System; class TwoDShape { double pri_width; // private double pri_height; // private // Default constructor. public TwoDShape() { width = height = 0.0; } // Constructor for TwoDShape. public TwoDShape(double w, double h) { width = w; height = h; } // Construct object with equal width and height. public TwoDShape(double x) { width = height = x; } // Properties for width and height. public double width { get { return pri_width; } set { pri_width = value; } } public double height { get { return pri_height; } set { pri_height = value; } } public void showDim() { Console.WriteLine("Width and height are " + width + " and " + height); } } // A derived class of TwoDShape for triangles. class Triangle : TwoDShape { string style; // private /* A default constructor. This automatically invokes the default constructor of TwoDShape. */ public Triangle() { style = "null"; } // Constructor that takes three arguments. public Triangle(string s, double w, double h) : base(w, h) { style = s; } // Construct an isosceles triangle. public Triangle(double x) : base(x) { style = "isosceles"; } // Return area of triangle. public double area() { return width * height / 2; } // Display a triangle's style. public void showStyle() { Console.WriteLine("Triangle is " + style); } } public class Shapes5 { public static void Main() { Triangle t1 = new Triangle(); Triangle t2 = new Triangle("right", 8.0, 12.0); Triangle t3 = new Triangle(4.0); t1 = t2; Console.WriteLine("Info for t1: "); t1.showStyle(); t1.showDim(); Console.WriteLine("Area is " + t1.area()); Console.WriteLine(); Console.WriteLine("Info for t2: "); t2.showStyle(); t2.showDim(); Console.WriteLine("Area is " + t2.area()); Console.WriteLine(); Console.WriteLine("Info for t3: "); t3.showStyle(); t3.showDim(); Console.WriteLine("Area is " + t3.area()); Console.WriteLine(); } }
Multilevel Hierarchy – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 *//* In a multilevel hierarchy, the first override of a virtual method that is found while moving up the heirarchy is the one executed. */ using System; class Base { // Create virtual method in the base class. public virtual void who() { Console.WriteLine("who() in Base"); } } class Derived1 : Base { // Override who() in a derived class. public override void who() { Console.WriteLine("who() in Derived1"); } } class Derived2 : Derived1 { // This class also does not override who(). } class Derived3 : Derived2 { // This class does not override who(). } public class NoOverrideDemo2 { public static void Main() { Derived3 dOb = new Derived3(); Base baseRef; // a base-class reference baseRef = dOb; baseRef.who(); // calls Derived1's who() } }
Multilevel Hierarchy 1 – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// A multilevel hierarchy. using System; class TwoDShape { double pri_width; // private double pri_height; // private // Default constructor. public TwoDShape() { width = height = 0.0; } // Constructor for TwoDShape. public TwoDShape(double w, double h) { width = w; height = h; } // Construct object with equal width and height. public TwoDShape(double x) { width = height = x; } // Properties for width and height. public double width { get { return pri_width; } set { pri_width = value; } } public double height { get { return pri_height; } set { pri_height = value; } } public void showDim() { Console.WriteLine("Width and height are " + width + " and " + height); } } // A derived class of TwoDShape for triangles. class Triangle : TwoDShape { string style; // private /* A default constructor. This invokes the default constructor of TwoDShape. */ public Triangle() { style = "null"; } // Constructor public Triangle(string s, double w, double h) : base(w, h) { style = s; } // Construct an isosceles triangle. public Triangle(double x) : base(x) { style = "isosceles"; } // Return area of triangle. public double area() { return width * height / 2; } // Display a triangle's style. public void showStyle() { Console.WriteLine("Triangle is " + style); } } // Extend Triangle. class ColorTriangle : Triangle { string color; public ColorTriangle(string c, string s, double w, double h) : base(s, w, h) { color = c; } // Display the color. public void showColor() { Console.WriteLine("Color is " + color); } } public class Shapes6 { public static void Main() { ColorTriangle t1 = new ColorTriangle("Blue", "right", 8.0, 12.0); ColorTriangle t2 = new ColorTriangle("Red", "isosceles", 2.0, 2.0); Console.WriteLine("Info for t1: "); t1.showStyle(); t1.showDim(); t1.showColor(); Console.WriteLine("Area is " + t1.area()); Console.WriteLine(); Console.WriteLine("Info for t2: "); t2.showStyle(); t2.showDim(); t2.showColor(); Console.WriteLine("Area is " + t2.area()); } }
Example Of Inheritance-Related Name Hiding – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// An example of inheritance-related name hiding. using System; class A { public int i = 0; } // Create a derived class. class B : A { new int i; // this i hides the i in A public B(int b) { i = b; // i in B } public void show() { Console.WriteLine("i in derived class: " + i); } } public class NameHiding { public static void Main() { B ob = new B(2); ob.show(); } }
Example Of Operator Overloading – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// An example of operator overloading. using System; // A three-dimensional coordinate class. class ThreeD { int x, y, z; // 3-D coordinates public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } // Overload binary +. public static ThreeD operator +(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); /* This adds together the coordinates of the two points and returns the result. */ result.x = op1.x + op2.x; // These are integer additions result.y = op1.y + op2.y; // and the + retains its original result.z = op1.z + op2.z; // meaning relative to them. return result; } // Overload binary -. public static ThreeD operator -(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); /* Notice the order of the operands. op1 is the left operand and op2 is the right. */ result.x = op1.x - op2.x; // these are integer subtractions result.y = op1.y - op2.y; result.z = op1.z - op2.z; return result; } // Show X, Y, Z coordinates. public void show() { Console.WriteLine(x + ", " + y + ", " + z); } } public class ThreeDDemo { public static void Main() { ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); ThreeD c = new ThreeD(); Console.Write("Here is a: "); a.show(); Console.WriteLine(); Console.Write("Here is b: "); b.show(); Console.WriteLine(); c = a + b; // add a and b together Console.Write("Result of a + b: "); c.show(); Console.WriteLine(); c = a + b + c; // add a, b and c together Console.Write("Result of a + b + c: "); c.show(); Console.WriteLine(); c = c - a; // subtract a Console.Write("Result of c - a: "); c.show(); Console.WriteLine(); c = c - b; // subtract b Console.Write("Result of c - b: "); c.show(); Console.WriteLine(); } }
Parameterized Constructor – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // A parameterized constructor. using System; class MyClass { public int x; public MyClass(int i) { x = i; } } public class ParmConsDemo { public static void Main() { MyClass t1 = new MyClass(10); MyClass t2 = new MyClass(88); Console.WriteLine(t1.x + " " + t2.x); } }
Program That Uses Building Class – Class Interface
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // A program that uses the Building class. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants } // This class declares an object of type Building. public class BuildingDemo { public static void Main() { Building house = new Building(); // create a Building object int areaPP; // area per person // assign values to fields in house house.occupants = 4; house.area = 2500; house.floors = 2; // compute the area per person areaPP = house.area / house.occupants; Console.WriteLine("house has:\n " + house.floors + " floors\n " + house.occupants + " occupants\n " + house.area + " total area\n " + areaPP + " area per person"); } }
Safe Method Of Determining Whether Class Implements Particular Interface – Class Interface
/* C# Programming Tips & Techniques by Charles Wright, Kris JamsaPublisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // ISample.cs - Demonstrates a safe method of determining whether a class // implements a particular interface // Compile this program with the following command line: // C:>csc isample.cs // namespace nsInterfaceSample { using System; public class InterfaceSample { static public void Main () { // Declare an instance of the clsSample class clsSample samp = new clsSample(); // Test whether clsSample supports the IDisposable interface if (samp is IDisposable) { // If true, it is safe to call the Dispose() method IDisposable obj = (IDisposable) samp; obj.Dispose (); } } } class clsSample : IDisposable { // Implement the IDispose() function public void Dispose () { Console.WriteLine ("Called Dispose() in clsSample"); } } }
Simple C# Class – Class Interface
using System;public class ASimpleClass { public static void Main() { Point myPoint = new Point(10, 15); Console.WriteLine("myPoint.x {0}", myPoint.x); Console.WriteLine("myPoint.y {0}", myPoint.y); } } class Point { // constructor public Point(int x, int y) { this.x = x; this.y = y; } // member fields public int x; public int y; }
Simple Class And Objects – Class Interface
public class Product { public string make; public string model; public string color; public int yearBuilt; public void Start() { System.Console.WriteLine(model + " started"); } public void Stop() { System.Console.WriteLine(model + " stopped"); }}class MainClass{ public static void Main() { Product myProduct; myProduct = new Product(); myProduct.make = "Toyota"; myProduct.model = "MR2"; myProduct.color = "black"; myProduct.yearBuilt = 1995; System.Console.WriteLine("myProduct details:"); System.Console.WriteLine("myProduct.make = " + myProduct.make); System.Console.WriteLine("myProduct.model = " + myProduct.model); System.Console.WriteLine("myProduct.color = " + myProduct.color); System.Console.WriteLine("myProduct.yearBuilt = " + myProduct.yearBuilt); myProduct.Start(); myProduct.Stop(); Product redPorsche = new Product(); redPorsche.make = "Porsche"; redPorsche.model = "Boxster"; redPorsche.color = "red"; redPorsche.yearBuilt = 2000; System.Console.WriteLine( "redPorsche is a " + redPorsche.model); System.Console.WriteLine("Assigning redPorsche to myProduct"); myProduct = redPorsche; System.Console.WriteLine("myProduct details:"); System.Console.WriteLine("myProduct.make = " + myProduct.make); System.Console.WriteLine("myProduct.model = " + myProduct.model); System.Console.WriteLine("myProduct.color = " + myProduct.color); System.Console.WriteLine("myProduct.yearBuilt = " + myProduct.yearBuilt); } }
