コード例 #1
0
ファイル: Program.cs プロジェクト: kevdhan/Csharp_dotnet
        static void Main(string[] args)
        {
            // by commenting out block of code below, we are using the constructor we created.
            // You will only get values for Make = Nissan
            // everything else will either be "" or 0 n
            Car myCar = new Car();

            /*
             * myCar.Make = "Oldmobile";
             * myCar.Model = "Cutlas Supreme";
             * myCar.Year = 1986;
             * myCar.Color = "Silver";
             */


            Car myOtherCar;     // creating a car object

            myOtherCar = myCar; // referencing same address

            Console.WriteLine("{0} {1} {2} {3}",
                              myOtherCar.Make, myOtherCar.Model,
                              myOtherCar.Year, myOtherCar.Color);

            myCar.Make = "NewOldMobile";
            Console.WriteLine(myOtherCar.Make); // further proof showing the reference of same address

            // null is not 0 or an empty string, simply means indetermined
            // myOtherCar = null; // dereferencing, null

            /*
             * Console.WriteLine("{0} {1} {2} {3}", // null refeence exception
             *  myOtherCar.Make, myOtherCar.Model,
             *  myOtherCar.Year, myOtherCar.Color);
             */

            myCar = null;
            Console.WriteLine("{0} {1} {2} {3}", // even though myCar was dereferenced, myOtherCar still points to the address with data
                              myOtherCar.Make, myOtherCar.Model,
                              myOtherCar.Year, myOtherCar.Color);


            // utilizing overloaded constructor
            Car myThirdCar = new Car("Ford", "Escape", 2005, "White");

            Console.WriteLine("{0} {1} {2} {3}",
                              myThirdCar.Make, myThirdCar.Model,
                              myThirdCar.Year, myThirdCar.Color);


            /* Question: How is that you can use certain classes without instantiating an object first?
             * An example is "Console.WriteLine()"
             * You are using the method WriteLine() from the class Console, but not instantiating
             * Answer: It is because the method is "Static"
             */

            Car.PrintCar(); // PrintCar() is a static method
        }