Boxing struct object : Boxing Unboxing « Data Types « C# / C Sharp






Boxing struct object

  

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

struct MyPoint {
    public int x, y;
}

class Program {
    public static void UseThisObject(object o) {
        Console.WriteLine("Type of param: {0}", o.GetType());
        Console.WriteLine("Value of o is: {0}", o);
    }

    public static void BoxAndUnboxInts() {
        
        ArrayList myInts = new ArrayList();
        myInts.Add(88);
        myInts.Add(3);
        myInts.Add(9764);

        int firstItem = (int)myInts[0];
        Console.WriteLine("First item is {0}", firstItem);
    }

    public static void UseBoxedMyPoint(object o) {
        if (o is MyPoint) {
            MyPoint p = (MyPoint)o;
            Console.WriteLine("{0}, {1}", p.x, p.y);
        } else
            Console.WriteLine("You did not send a MyPoint.");
    }


    static void Main(string[] args) {
        int myInt = 99;

        UseThisObject(myInt);
        BoxAndUnboxInts();

        MyPoint p;
        p.x = 10;
        p.y = 20;
        UseBoxedMyPoint(p);
        UseBoxedMyPoint(1);
    }
}

   
  








Related examples in the same category

1.implicit boxing of an int
2.explicit boxing of an int to an object
3.explicit unboxing of an object to an int
4.A simple boxing/unboxing exampleA simple boxing/unboxing example
5.Boxing also occurs when passing valuesBoxing also occurs when passing values
6.Boxing makes it possible to call methods on a valueBoxing makes it possible to call methods on a value
7.Illustrates boxing and unboxingIllustrates boxing and unboxing
8.Automatic boxing and unboxing to pass an undetermined data type to a functionAutomatic boxing and unboxing to pass an undetermined data type to a function
9.is and Box UnBoxis and Box UnBox
10.Box to object