All pastes #1749793 Raw Edit

Keyword usage: ref and out

public text v1 · immutable
#1749793 ·published 2010-01-13 16:33 UTC
rendered paste body
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program().Run();

            Console.WriteLine("Press any key to exit . . .");
            Console.ReadKey(true);
        }

        public void Run()
        {
            Blah b = Dao.GetBlah(23);

            SomeService.ModifyXml(b);    // do I need to use out or ref here?
            Dao.SaveXml(b.Xml);

            SomeService.SubstituteNew(out b);
            Dao.SaveXml(b.Xml);
            
            SomeService.ReadThenReplace(ref b);
            Dao.SaveXml(b.Xml);
        }

        private class Blah
        {
            public int Id { get; set; }
            public string Xml
            {
                get
                {
                    return "<Id>" + this.Id + "<Id>";
                }
            }
        }

        private static class Dao
        {
            public static Blah GetBlah(int id)
            {
                return new Blah() { Id = id };
            }

            public static void SaveXml(string blahXml)
            {
                Console.WriteLine(blahXml);
            }
        }

        private static class SomeService
        {
            public static void ModifyXml(Blah b)
            {
                b.Id = 17;
            }

            public static void SubstituteNew(out Blah b)
            {
                // The 'out' keyword means the parameter itself cannot
                // be read from until you have assigned a new value.

                // Compile error on this line, uninitialized variable.
                //Console.WriteLine(b.Id);

                // You cannot exit the method until you have assigned a new value.
                b = new Blah() { Id = 99 };
            }

            public static void ReadThenReplace(ref Blah b)
            {
                // The 'ref' keyword means you can replace
                //  the incoming reference with a new one.

                // You can access the incoming reference immediately.
                Console.WriteLine(b.Id);

                if (DateTime.Now.IsDaylightSavingTime())
                {
                    // You are not required to replace the reference.
                    b = new Blah() { Id = -18 };
                }
            }
        }
    }
}