Pages

Tuesday, April 8, 2014

Target platforms: Any CPU vs x86 vs x64

A lot of developers misinterpret the meaning of "Target platform" option in Visual Studio. You can read a good explanation here. I don't want to take credit for others work, so I just summarize the 5 most important facts:
  • "Any CPU, means that the assembly will run natively on the CPU is it currently running on.", however "Any CPU does not guarantee that it will run on both 32-bit and 64-bit Windows." (if it has 32-bit dependencies, but not marked - author)
  • "[...] this setting actually does not affect the build of the assembly in any way except to set the platform status information on the assembly’s CLR header."
  • "Reasons to set your project as x86 include dependencies upon native DLLs that are only available in 32-bit"
  • "[...] assemblies marked for x86 can still run on 64-bit Windows."
  • "All assemblies targeting .Net 1.0 and 1.1 will be 32-bit only (x86) [...]"
Don't forget to read the whole article to have a better understanding :)



Monday, April 7, 2014

The differece between "new" and "override"

However the keyword new and the keyword override are very alike, they have some really different purpose and it is not recommended to swap / mix them. You can read their behaviors and purposes e.g. on StackOverflow

Here is an example for the article above. As you can see, you will have different result, which can cause you some headache if you try to find a bug.

   public class Base
   {
      public virtual void Method()
      {
         Debug.WriteLine("Base");
      }
   }

   public class Override : Base
   {
      public override void Method()
      {
         Debug.WriteLine("Override");
      }
   }

   public class New : Base 
   {
      public new void Method()
      {
         Debug.WriteLine("New");
      }
   }

   public class Program
   {
      public Program()
      {
         var b = new Base();
         b.Method(); // "Base"

         b = new Override();
         b.Method(); // "Override"
         
         b = new New();
         b.Method(); // "Base"
      }

      static void Main(string[] args)
      {
         var p = new Program();
      }
   }

Unfortunately C# compiler has a really bad behavior and let you to hide a method without explicitly write new. Ohh, yeah... you will get a warning, but not a compile error nor a runtime error. All you are going to face with, is some unwanted misbehavior. So, watch out.