C# - test and cast with reference type or value...

Please check the following code snippet for test and cast on references types (exemplified by a string object), or a value type , represented by a int type.

also, the special case of 0 is considered.
[Test]
        public void TestConvertNullToString()
        {
            var a = ((string) null);
            if (a == null)
            {
                Console.WriteLine("Hello");
            }
            else
            {
              Console.WriteLine("bbb");   
            }


            if (a is string)
            {
                Console.WriteLine("a is String");
            }
            else
            {
                Console.WriteLine("a is not String");
            }

            if (a is int)
            {
                Console.WriteLine("a is int");
            }
            else
            {
                Console.WriteLine("a is not int");
            }

//            if ((a as int) == null)
//            {
//                Console.WriteLine("a is not String");}
//
//            }
//            else
//            {
//               Console.WriteLine("a is not String");
//            }

            int c = 1;
            object d = c;
            a = ((string) d); // Invalid cast exception

            Assert.DoesNotThrow(() => { string.IsNullOrEmpty((string) null); });
        }
    }
}

你可能感兴趣的:(C#)