The ref you do not know

Source: Internet
Author: User

In C #, there is a keyword called ref, which is used to transmit parameters by reference. The basic usage is as follows:

 1 class RefExample 2 { 3     static void Method(ref int i) 4     { 5         i = 44; 6     } 7     static void Main() 8     { 9         int val = 0;10         Method(ref val);11         // val is now 4412     }13 }

It can be seen that when the keyword ref is used, when the function declaration can be called, The ref must be added to the parameter; otherwise, the compiler will prompt an error:

But is that true?

See the following code.

 1 public class Class1 2     { 3         public int Int { get; set; } 4         public DateTime Time { get; set; } 5     } 6     [ComImport, Guid("B2E23B44-FD50-4131-94C7-7D9569837289")] 7     interface ITestClass 8     { 9         void TestFunc(ref int i, ref DateTime t);10     }11     class TestClass : ITestClass12     {13         public void TestFunc(ref int i, ref DateTime t)14         {15         }16         public static void Main()17         {18             ITestClass test = new TestClass();19             var obj = new Class1();20             test.TestFunc(obj.Int, obj.Time);21         }22     }

Did you find anything special? By the way, there are 20th rows of function calls. You are not mistaken. when calling the function, you did not add a ref, but the code was compiled (I tested it in vs2010). Isn't that amazing.

The focus of this Code is to declare the interface as a COM object interface, that is, to add the comimport and guid attributes, and then add the ref when calling the functions in the interface, if you remove comimport, the compiler immediately returns an error message.

I guess it may be related to the call of COM, but I have just been familiar with COM and have little knowledge about C # Calling com. Therefore, I cannot explain this wonderful syntax. I don't know who knows much about this. Please leave a message below!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.