C# type inference

Step1/API/TypeInference.cs

using System;

namespace Step1.API
{
    class TypeInference
    {
        public static void PrintType()
        {
            var a = 10;
            var b = 10.23;
            var c = "Hello";
            var d = false;

            Console.WriteLine("a:"+a.GetType());
            Console.WriteLine("b:" + b.GetType());
            Console.WriteLine("c:" + c.GetType());
            Console.WriteLine("d:" + d.GetType());
            Console.WriteLine();
        }
    }
}

Step1/Run.cs

using System;
using Step1.API;
namespace Step1
{
    class Run
    {
        public static  int Main(String[] args)
        {
            //helloworld.printhello();
            TypeInference.PrintType();
            return 0;
        }
    }
}

Running result
a:System.Int32
b:System.Double
c:System.String
d:System.Boolean

Some rules need to be followed:

  • Variables must be initialized. Otherwise, the compiler has no basis for inferring the variable type.
  • Initializers cannot be null.
  • Initializers must be placed in expressions.
  • An initializer cannot be set to an object unless a new object is created in the initializer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733060&siteId=291194637