Utilize MyClass without assuming any prior knowledge

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Utilize MyClass without assuming any prior knowledge.

using System;
using System.Reflection;

public class ReflectAssemblyDemo1 {
public static void Main() {
int val;
Assembly asm = Assembly.LoadFrom(“MyClasses.exe”);

Type[] alltypes = asm.GetTypes();

Type t = alltypes[0]; // use first class found

Console.WriteLine(“Using: ” + t.Name);

ConstructorInfo[] ci = t.GetConstructors();

// Use first constructor found.
ParameterInfo[] cpi = ci[0].GetParameters();
object reflectOb;

if(cpi.Length > 0) {
object[] consargs = new object[cpi.Length];

// initialize args
for(int n=0; n < cpi.Length; n++) consargs[n] = 10 + n * 20; // construct the object reflectOb = ci[0].Invoke(consargs); } else reflectOb = ci[0].Invoke(null); Console.WriteLine(" Invoking methods on reflectOb."); Console.WriteLine(); // Ignore inherited methods. MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ; // Invoke each method. foreach(MethodInfo m in mi) { Console.WriteLine("Calling {0} ", m.Name); // Get the parameters ParameterInfo[] pi = m.GetParameters(); // Execute methods. switch(pi.Length) { case 0: // no args if(m.ReturnType == typeof(int)) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("Result is " + val); } else if(m.ReturnType == typeof(void)) { m.Invoke(reflectOb, null); } break; case 1: // one arg if(pi[0].ParameterType == typeof(int)) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); else Console.WriteLine("14 is not between x and y"); } break; case 2: // two args if((pi[0].ParameterType == typeof(int)) && (pi[1].ParameterType == typeof(int))) { object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if((pi[0].ParameterType == typeof(double)) && (pi[1].ParameterType == typeof(double))) { object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } break; } Console.WriteLine(); } } } //============================================================== /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // A file that contains three classes. Call this file MyClasses.cs. using System; class MyClass { int x; int y; public MyClass(int i) { Console.WriteLine("Constructing MyClass(int). "); x = y = i; show(); } public MyClass(int i, int j) { Console.WriteLine("Constructing MyClass(int, int). "); x = i; y = j; show(); } public int sum() { return x+y; } public bool isBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void set(int a, int b) { Console.Write("Inside set(int, int). "); x = a; y = b; show(); } // Overload set. public void set(double a, double b) { Console.Write("Inside set(double, double). "); x = (int) a; y = (int) b; show(); } public void show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); } } class AnotherClass { string remark; public AnotherClass(string str) { remark = str; } public void show() { Console.WriteLine(remark); } } public class Demo12 { public static void Main() { Console.WriteLine("This is a placeholder."); } } [/csharp]

Locate an assembly, determine types, and create an object using reflection

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* Locate an assembly, determine types, and create
an object using reflection. */

using System;
using System.Reflection;

public class ReflectAssemblyDemo {
public static void Main() {
int val;

// Load the MyClasses.exe assembly.
Assembly asm = Assembly.LoadFrom(“MyClasses.exe”);

// Discover what types MyClasses.exe contains.
Type[] alltypes = asm.GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(“Found: ” + temp.Name);

Console.WriteLine();

// Use the first type, which is MyClass in this case.
Type t = alltypes[0]; // use first class found
Console.WriteLine(“Using: ” + t.Name);

// Obtain constructor info.
ConstructorInfo[] ci = t.GetConstructors();

Console.WriteLine(“Available constructors: “);
foreach(ConstructorInfo c in ci) {
// Display return type and name.
Console.Write(” ” + t.Name + “(“);

// Display parameters.
ParameterInfo[] pi = c.GetParameters();

for(int i=0; i < pi.Length; i++) { Console.Write(pi[i].ParameterType.Name + " " + pi[i].Name); if(i+1 < pi.Length) Console.Write(", "); } Console.WriteLine(")"); } Console.WriteLine(); // Find matching constructor. int x; for(x=0; x < ci.Length; x++) { ParameterInfo[] pi = ci[x].GetParameters(); if(pi.Length == 2) break; } if(x == ci.Length) { Console.WriteLine("No matching constructor found."); return; } else Console.WriteLine("Two-parameter constructor found. "); // Construct the object. object[] consargs = new object[2]; consargs[0] = 10; consargs[1] = 20; object reflectOb = ci[x].Invoke(consargs); Console.WriteLine(" Invoking methods on reflectOb."); Console.WriteLine(); MethodInfo[] mi = t.GetMethods(); // Invoke each method. foreach(MethodInfo m in mi) { // Get the parameters ParameterInfo[] pi = m.GetParameters(); if(m.Name.CompareTo("set")==0 && pi[0].ParameterType == typeof(int)) { // This is set(int, int). object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if(m.Name.CompareTo("set")==0 && pi[0].ParameterType == typeof(double)) { // This is set(double, double). object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } else if(m.Name.CompareTo("sum")==0) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("sum is " + val); } else if(m.Name.CompareTo("isBetween")==0) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); } else if(m.Name.CompareTo("show")==0) { m.Invoke(reflectOb, null); } } } } //================================================================ /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // A file that contains three classes. Call this file MyClasses.cs. using System; class MyClass { int x; int y; public MyClass(int i) { Console.WriteLine("Constructing MyClass(int). "); x = y = i; show(); } public MyClass(int i, int j) { Console.WriteLine("Constructing MyClass(int, int). "); x = i; y = j; show(); } public int sum() { return x+y; } public bool isBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void set(int a, int b) { Console.Write("Inside set(int, int). "); x = a; y = b; show(); } // Overload set. public void set(double a, double b) { Console.Write("Inside set(double, double). "); x = (int) a; y = (int) b; show(); } public void show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); } } class AnotherClass { string remark; public AnotherClass(string str) { remark = str; } public void show() { Console.WriteLine(remark); } } public class Demo12 { public static void Main() { Console.WriteLine("This is a placeholder."); } } [/csharp]

Demonstrate dynamically invoking an object

   

/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Invoke.cs -- Demonstrate dynamically invoking an object
//
//              Compile this program with the following command line:
//                  C:>csc Invoke.cs
using System;
using System.Reflection;

namespace nsReflection
{
    public class Invoke
    {
        static public void Main ()
        {
            // Load the Circle assembly.
            Assembly asy = null;
            try
            {
                asy = Assembly.Load ("Circle");
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                return;
            }
            
            // Parameter array for a POINT object.
            object [] parmsPoint = new object [2] {15, 30};
            
            // Parameter array for a clsCircle object.
            object [] parmsCircle = new object [3] {100, 15, 30};
            
            // Get the type of clsCircle and create an instance of it.
            Type circle = asy.GetType("nsCircle.clsCircle");
            object obj = Activator.CreateInstance (circle, parmsCircle);
            
            // Get the property info for the area and show the area
            PropertyInfo p = circle.GetProperty ("Area");
            Console.WriteLine ("The area of the circle is " + p.GetValue(obj, null));
            
            // Get the POINT type and create an instance of it
            Type point = asy.GetType("nsCircle.POINT");
            object pt = Activator.CreateInstance (point, parmsPoint);
            
            // Show the point using object&#039;s ToString() method
            Console.WriteLine ("The point is " + pt.ToString ());
        }
    }
}


           
          


Using reflection to get information about an assembly

   

/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Asy.cs -- Demonstrates using reflection to get information
//           about an assembly.
//
//           Compile this program with the following command line:
//               C:>csc Asy.cs
using System;
using System.Reflection;

public class Asy
{
    static public void Main ()
    {
        Assembly asy = null;
        try
        {
            asy = Assembly.Load ("Circle");
        }
        catch (Exception e)
        {
            Console.WriteLine (e.Message);
            return;
        }
        Type [] types = asy.GetTypes();
        foreach (Type t in types)
            ShowTypeInfo (t);
    }
    static void ShowTypeInfo (Type t)
    {
            Console.WriteLine ("{0} is a member of the {1} namespace", t.Name, t.Namespace);
            Console.WriteLine ("
Methods in {0}:", t.Name);
            MethodInfo [] methods = t.GetMethods ();
            foreach (MethodInfo m in methods)
                Console.WriteLine ("	" + m.Name);
            Console.WriteLine ("
Properties in {0}:", t.Name);
            PropertyInfo [] props = t.GetProperties ();
            foreach (PropertyInfo p in props)
                Console.WriteLine ("	" + p.Name);
            Console.WriteLine ("
Fields in {0}:", t.Name);
            FieldInfo [] fields = t.GetFields ();
            foreach (FieldInfo f in fields)
                Console.WriteLine ("	" + f.Name);
    }
}


           
          


Random Color and Rectangle

   
 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class RandomRectangle: Form
{
     public static void Main()
     {
          Application.Run(new RandomRectangle());
     }
     public RandomRectangle()
     {
          Text = "Random Rectangle";
   
          Timer timer    = new Timer();
          timer.Interval = 1;
          timer.Tick    += new EventHandler(TimerOnTick);
          timer.Start();
     }
     void TimerOnTick(object obj, EventArgs ea)
     {
          Random rand = new Random();
   
          int x1 = rand.Next(ClientSize.Width);
          int x2 = rand.Next(ClientSize.Width);
          int y1 = rand.Next(ClientSize.Height);
          int y2 = rand.Next(ClientSize.Height);
   
          Color color = Color.FromArgb(rand.Next(256), 
                                       rand.Next(256), 
                                       rand.Next(256));
   
          Graphics grfx = CreateGraphics();
          grfx.FillRectangle(new SolidBrush(color), 
                             Math.Min(x1,  x2), Math.Min(y1,  y2),
                             Math.Abs(x2 - x1), Math.Abs(y2 - y1));
          grfx.Dispose();
     }
}

    


Roll a six-sided die 6000 times.

using System;

public class RollDie
{
public static void Main( string[] args )
{
Random randomNumbers = new Random();

int frequency1 = 0;
int frequency2 = 0;
int frequency3 = 0;
int frequency4 = 0;
int frequency5 = 0;
int frequency6 = 0;

int face;

for ( int roll = 1; roll <= 6000; roll++ ) { face = randomNumbers.Next( 1, 7 ); switch ( face ) { case 1: frequency1++; break; case 2: frequency2++; break; case 3: frequency3++; break; case 4: frequency4++; break; case 5: frequency5++; break; case 6: frequency6++; break; } } Console.WriteLine( "Face Frequency" ); // output headers Console.WriteLine( "1 {0} 2 {1} 3 {2} 4 {3} 5 {4} 6 {5}", frequency1, frequency2, frequency3, frequency4, frequency5, frequency6 ); } } [/csharp]