/* 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()); } }
Class Interface
Constructor overloading 3
/* * C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: */ using System; namespace Client.Chapter_5___Building_Your_Own_Classes { public class CTORChapter { public int[] MyIntArray; public int Y; //Initialization can take place here private int ObjectCount = 0; static void Main(string[] args) { CTORChapter X = new CTORChapter(); X.ObjectCount++; CTORChapter YY = new CTORChapter(10); } //Default CTORChapter CTORChapter() { MyIntArray = new int[10]; //Do work necessary during object creation } //Overloads the CTOR allowing you to initialize Y CTORChapter(int myY) { Y = myY; } } }
Check the parameter in construtor
using System;
public class Class1 {
public static void Main(string[] args) {
Student student = new Student(“AAA”, 1234);
Console.WriteLine(“Welcome new student {0}”, student.GetString());
}
}
public class Student {
string sStudentName;
int nStudentID;
int nCreditHours;
public Student(string sName, int nID) {
if (sName == null) {
sName = “invalid”;
}
sStudentName = sName;
if (nID < 0) { nID = 0; } nStudentID = nID; nCreditHours = 0; } public string GetString() { string s = String.Format("{0}({1})",sStudentName, nStudentID); return s; } } [/csharp]
constructor initializers are called bottom-up but the constructors are invoked top-down starting with the constructor in the base class
using System; public class Starter { public static void Main() { XClass obj = new XClass(); } } public class MyClass { public MyClass(int param) { Console.WriteLine("MyClass constructor"); } } public class YClass : MyClass { public YClass(int param) : base(YClass.MethodA()) { Console.WriteLine("YClass constructor"); } public static int MethodA() { Console.WriteLine("YClass constructor initializer"); return 0; } } public class XClass : YClass { public XClass() : base(XClass.MethodA()) { Console.WriteLine("XClass constructor"); } public static new int MethodA() { Console.WriteLine("XClass constructor initializer"); return 0; } }
Clone an Object
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; namespace WOSI.Utilities { public class ObjectUtils { public static object Clone(object objectToClone) { object dataObject = Activator.CreateInstance(objectToClone.GetType()); // Fill in our class fields foreach (System.Reflection.FieldInfo field in dataObject.GetType().GetFields()) { try { if (field.IsPublic) { field.SetValue(dataObject, objectToClone.GetType().GetField(field.Name).GetValue(objectToClone)); } } catch { } } // Fill in our class properties foreach (System.Reflection.PropertyInfo property in dataObject.GetType().GetProperties()) { try { if (property.PropertyType.IsPublic && property.CanWrite) { property.SetValue(dataObject, objectToClone.GetType().GetProperty(property.Name).GetValue(objectToClone, null), null); } } catch { } } return dataObject; } } }
Implements ICloneable
using System; using System.Text; using System.Collections.Generic; public class Employee : ICloneable { public string Name; public string Title; public int Age; public Employee(string name, string title, int age) { Name = name; Title = title; Age = age; } public object Clone() { return MemberwiseClone(); } public override string ToString() { return string.Format("{0} ({1}) - Age {2}", Name, Title, Age); } } public class Team : ICloneable { public List<Employee> TeamMembers = new List<Employee>(); public Team() { } private Team(List<Employee> members) { foreach (Employee e in members) { TeamMembers.Add((Employee)e.Clone()); } } public void AddMember(Employee member) { TeamMembers.Add(member); } public override string ToString() { StringBuilder str = new StringBuilder(); foreach (Employee e in TeamMembers) { str.AppendFormat(" {0} ", e); } return str.ToString(); } public object Clone() { return new Team(this.TeamMembers); } } public class MainClass { public static void Main() { Team team = new Team(); team.AddMember(new Employee("F", "Developer", 34)); team.AddMember(new Employee("K", "Tester", 78)); team.AddMember(new Employee("C", "Support", 18)); Team clone = (Team)team.Clone(); Console.WriteLine(team); Console.WriteLine(clone); Console.WriteLine(Environment.NewLine); team.TeamMembers[0].Name = "NewName"; team.TeamMembers[0].Title = "Manager"; team.TeamMembers[0].Age = 44; Console.WriteLine(team); Console.WriteLine(clone); } }
System.Array and the Collection Classes:ICloneable 2
using System; class ContainedValue { public ContainedValue(int count) { this.count = count; } public int count; } class MyObject { public MyObject(int count) { this.contained = new ContainedValue(count); } public MyObject Clone() { return((MyObject) MemberwiseClone()); } public ContainedValue contained; } public class SystemArrayandtheCollectionClassesICloneable2 { public static void Main() { MyObject my = new MyObject(33); MyObject myClone = my.Clone(); Console.WriteLine("Values: {0} {1}",my.contained.count, myClone.contained.count); myClone.contained.count = 15; Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count); } }