예제 #1
0
        public void EnumParsing_WithoutExtensions()
        {
            // Note that you can't parse directly to the property. You need
            // to use temporary variables. Consider this method an example of
            // steps you'd normally take when parsing enums.
            RandomModelObject obj           = new RandomModelObject();
            AnimalTypeEnum    tmpAnimalEnum = AnimalTypeEnum.Bird;

            Enum.TryParse <AnimalTypeEnum>("Cat", out tmpAnimalEnum);
            obj.NonNullableEnum = tmpAnimalEnum;
            Assert.AreEqual(AnimalTypeEnum.Cat, obj.NonNullableEnum, "Should have parsed to Cat type. ('Cat')");


            Enum.TryParse <AnimalTypeEnum>("3", out tmpAnimalEnum);  // we can also parse with values.
            obj.NonNullableEnum = tmpAnimalEnum;
            Assert.AreEqual(AnimalTypeEnum.Dog, obj.NonNullableEnum, "Should have parsed to Dog type.('3')");


            // For nullable values this can get annoying. A one-liner would be nice.
            AnimalTypeEnum tmpAnimalEnum2;

            if (Enum.TryParse <AnimalTypeEnum>("Dog", out tmpAnimalEnum))
            {
                obj.NullableEnum = tmpAnimalEnum;
            }
            else
            {
                obj.NullableEnum = null;
            }
            Assert.AreEqual(AnimalTypeEnum.Dog, obj.NullableEnum, "Should have parsed to nullable Dog type.");
        }
예제 #2
0
        public void EnumParsing_WithExtensions()
        {
            // Thanks to the one-liner, you can parse right to the property.
            RandomModelObject obj = new RandomModelObject()
            {
                NonNullableEnum = "Cat".ToNullable <AnimalTypeEnum>() ?? AnimalTypeEnum.Bird,
                NullableEnum    = "3".ToNullable <AnimalTypeEnum>() // Should be the dog type.
            };

            Assert.AreEqual(AnimalTypeEnum.Cat, obj.NonNullableEnum, "Should be parsed to Cat type. ('Cat')");
            Assert.AreEqual(AnimalTypeEnum.Dog, obj.NullableEnum, "Should be parsed to Dog type.('Dog')");

            // These will fail to parse and will return null.
            Assert.IsNull("This won't parse".ToNullable <AnimalTypeEnum>(), "Note that bad inputs from forms will be handled just fine.");
            Assert.IsNull("".ToNullable <AnimalTypeEnum>(), "Note that bad inputs from forms will be handled just fine.");
        }