int and Int32 are actually the same thing and how they derive from Object. - CSharp Language Basics

CSharp examples for Language Basics:int

Description

int and Int32 are actually the same thing and how they derive from Object.

Demo Code

using System;/*from w  w w .  ja va 2 s  .c  o  m*/
public class Program
{
   public static void Main(string[] args)
   {
      int i = new int();  // Yes, you can do this.
      i = 1;
      OutputMethod(i);
      OutputMethod(2);
      Console.WriteLine("Output directly = {0}", 3.ToString());
      Console.WriteLine("\nPick the integers out of a list:");
      object[] objects = { "this is a string", 2, new Program(), 4, 5.5 };
      for(int index = 0; index < objects.Length; index++)
      {
         if (objects[index] is int)
         {
            int n = (int)objects[index];  // This cast involves "unboxing."
            // index and n must be boxed when passed to WriteLine.
            Console.WriteLine("the {0}th element is a {1}", index, n);
         }
      }
      Console.WriteLine("\nDisplay all the objects in the list:");
      int count = 0;
      foreach(object o in objects)
      {
         Console.WriteLine("Objects[{0}] is <{1}>",
         count++, o.ToString());  // Calling ToString() prevents unboxing.
      }
   }
   public static void OutputMethod(IFormattable id)
   {
      Console.WriteLine("Value from OutputMethod = {0}", id.ToString());
   }
   override public string ToString()
   {
      return "TypeUnification Program";
   }
}

Result


Related Tutorials