Navigate to Post

Monday, April 6, 2020

Learn C#~#3 USING DECLARATIONS

Using statements are a convenient way to write code which ensures that an IDisposable object is correctly disposed of. A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.


PROGRAM



using System;

namespace MyTestConsole
{
    class Program
    {
        static void Main()
        {

            //Old way
            using (var printMeOld = new PrintMe())
            {
                printMeOld.PrintSomething("OLD WAY");
            }

            //New way
            using var printMe = new PrintMe();
            printMe.PrintSomething("NEW WAY");
            Console.ReadKey();
        }
    }
    public class PrintMe : IDisposable
    {
        public void PrintSomething(string keyword)
        {
            Console.WriteLine($"{keyword} of Printing Something");
        }
        public void Dispose()
        {
        }
    }
}

OUTPUT




All time trending post