Thursday, October 29, 2015

Mishmash instance and static in C#? What happens?

First of all, this will not compile!

namespace Whatever.Models
{
   public static class Flapdoodle
   {
      public string Bar()
      {
         return "Bar";
      }
   }
}

 
 

Static classes must have to have static methods, but what if we have something like this instead for our Flapdoodle class?

namespace Whatever.Models
{
   public class Flapdoodle
   {
      public static string Foo()
      {
         return "Foo";
      }
      
      public string Bar()
      {
         return "Bar";
      }
   }
}

 
 

Some observations about this are...

  1. Alright, this cannot compile.
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Whatever.Models;
    namespace Whatever.Tests
    {
       [TestClass]
       public class UnitTest
       {
          [TestMethod]
          public void Test()
          {
             Assert.AreEqual(Flapdoodle.Bar(), "Bar");
          }
       }
    }


     
  2. And, neither can this:
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Whatever.Models;
    namespace Whatever.Tests
    {
       [TestClass]
       public class UnitTest
       {
          [TestMethod]
          public void Test()
          {
             Flapdoodle bosh = new Flapdoodle();
             Assert.AreEqual(bosh.Foo(), "Foo");
          }
       }
    }

     
  3. This compiles and the test passes too.
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Whatever.Models;
    namespace Whatever.Tests
    {
       [TestClass]
       public class UnitTest
       {
          [TestMethod]
          public void Test()
          {
             Assert.AreEqual(Flapdoodle.Foo(), "Foo");
             Flapdoodle bosh = new Flapdoodle();
             Assert.AreEqual(bosh.Bar(), "Bar");
          }
       }
    }

     

By the way, you cannot have a static struct but you can put static methods in a struct that is not static. The behavior is the same as what is documented above for a similar situation with an instance class (Flapdoodle) which has a mix of static and instance methods.

No comments:

Post a Comment