Saturday, May 19, 2012

using string.Format with flags enums

Page 231 of "C# 4.0 in a Nutshell" illustrates that one may use string.Format to get back a string representation of the values of a flags enum!

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
namespace Whatever.Tests
{
   [TestClass]
   public class BorderTests
   {
      [TestMethod]
      public void Test()
      {
         Border border = Border.Top | Border.Left;
         Assert.AreEqual((int)border, 4 + 1);
         string combination = string.Format("{0:F}", border);
         Assert.AreEqual(combination,"Left, Top");
      }
   }
}

 
 

Here is a flags enum:

using System;
namespace Whatever.Models
{
   [Flags]
   public enum Border
   {
      Left=1,
      Right=2,
      Top=4,
      Bottom=8
   }
}

No comments:

Post a Comment