C # example (-)-implicit Declaration

Source: Internet
Author: User

You can use var to declare a variable. The declared variable type is determined by the type of the variable value initialized,
This is a bit like the variant in VB6.0.

Class Program {static void Main (string [] args) {// declare with the var keyword, var I = 0; // declare that the class Program must be initialized // var I; // cannot be empty initially // var I = null; Console. writeLine (I); // value can be assigned again // I = 10; // value cannot be assigned to another type // I = "0"; Console. writeLine (I); // using var declaration can be assigned to different types of values. Its type is determined by the type of the initialized value var s = "Hello C #3.0"; Console. writeLine (s); // declared array var num = new [] {0, 1, 2}; foreach (int n in num) {Console. writeLine (n);} // You can also output foreach (var n in num) {Console. writeLine (n);} // declared object var student = new {Name = "Xiao qiushui", Age = 23}; Console. writeLine ("Hero {0}", student. name) ;}} class TestVar {// class member cannot be declared // var s = "abc"; public void TestMethod () {// you can declare the method local variable var n = 10 ;}}

Summary:
1. Use var to declare a variable. The declared variable type is determined by the type of the variable value initialized.
2. The declaration must be initialized and cannot be empty initially.
3. This variable cannot be assigned another value of the data type.
4. An array can be declared.
5. objects that can be declared
6. Class Members cannot be declared. Only local variables can be used.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.