March, 2004

  • Eric Gunnerson's Compendium

    New Column - different methods of dynamic dispatch.



    Executive summary: Avoid Type.InvokeMember() if you can.


  • Eric Gunnerson's Compendium

    Why does C# require 'ref' and 'out' at both definition and use?


    (question from a customer)

    If you use 'ref' or 'out' on a method parameter:

    class Test
        public void Process(ref int t)

    when you call it you need to specify 'ref':

    Test t = new Test();
    int val = 5;

    t.Process(ref val);

    We require you to include 'ref' or 'out' to improve the readability of your code. Anybody who looks at the call above can tell that the value of val might be changed during the call. Otherwise, you'd have to find the definition, which would be much more difficult.

    [Update: Ferris asks “why can't you use ref with a property?” As Daniel points out, this could lead to some problems with your code, especially in multi-threaded cases. The compiler could handle those cases, but only through synchronization (at least in the general case), which wouldn't do good things for performance. I think we made the right choice not trying to do this in the compiler.

    Oh, and Ferris, it's really hard to take you serious with that name...]

    [Update: Richard asks “Why do I have to have a SecurityPermission in my manifest if I use unsafe to define a parameter as a pointer, but not if I define it as a ref?”

    Calling Interop code also requires permissions - SecurityPermission IIRC - which means that there isn't a real difference in the amount of permission required to run the code.]

Page 2 of 2 (27 items) 12