简体   繁体   中英

Does an int field have a default of 0?

I have a Console app with the following code:

    using System;

    namespace HeadfirstPage210bill
    {
        class Program
        {
            static void Main(string[] args)
            {
                CableBill myBill = new CableBill(4);
                Console.WriteLine(myBill.iGotChanged);
                Console.WriteLine(myBill.CalculateAmount(7).ToString("£##,#0.00"));
                Console.WriteLine("Press enter to exit");
                Console.WriteLine(myBill.iGotChanged);
                Console.Read();
            }
        }
    }

The class CableBill.cs is the following:

    using System;

    namespace HeadfirstPage210bill
    {
        class CableBill
        {
            private int rentalFee;
            public CableBill(int rentalFee) {
                iGotChanged = 0;
                this.rentalFee = rentalFee;
                discount = false;
            }

            public int iGotChanged = 0;


            private int payPerViewDiscount;
            private bool discount;
            public bool Discount {
                set {
                    discount = value;
                    if (discount) {
                        payPerViewDiscount = 2;
                        iGotChanged = 1;
                    } else {
                        payPerViewDiscount = 0;
                        iGotChanged = 2;
                    }
                }
            }

            public int CalculateAmount(int payPerViewMoviesOrdered) {
                return (rentalFee - payPerViewDiscount) * payPerViewMoviesOrdered;
            }

        }
    }

The console is returning the following:

在此输入图像描述

What I can not see is when payPerViewDiscount is set to 0. Surely this can only happen when the Discount property is set but if the property Discount is called then the variable iGotChanged should be returning 1 or 2, but it seems to stay on 0. Because it is type int is there a default value for payPerViewDiscount of 0?

yes the default value of int is 0 you can check using the default keyword

int t = default(int);

t will hold 0

Fields in a class are initialized to their default value before the constructor runs. The default value for an int is 0.

Please note that this does not apply for local variables, eg in methods. They won't be initialized automatically.

public class X
{
    private int _field;

    public void PrintField()
    {
        Console.WriteLine(_field); // prints 0
    }

    public void PrintLocal()
    {
        int local;
        Console.WriteLine(local); 
        // yields compiler error "Use of unassigned local variable 'local'"
    }
}

Exactly. int default value is 0 .

是的,零是int的默认值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM