Advertising
Paste Description for Keyword usage: ref and out
From this question:
http://stackoverflow.com/questions/2058161/do-you-need-the-ref-or-out-parameter
- Keyword usage: ref and out
- Wednesday, January 13th, 2010 at 9:33:25am MST
- using System;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- 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)
- {
- }
- 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.
- }
- 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.
- }
- }
- }
- }
- }
advertising
Update the Post
Either update this post and resubmit it with changes, or make a new post.
You may also comment on this post.
Please note that information posted here will expire by default in one month. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.