Tech Off Post

Single Post Permalink

View Thread: Reference Parameters in C#
  • User profile image

    Trivial.  C# params by default are "in" params you pass reference to existing object and downcast allowed, also you can use "out" specifier to specify that you expect value returned and well you can use "ref" to specify that value is both in and out.

    In case if you have IFooBar then you can downcast to IFoo then pass as input param, but IFoo object returned from method can not casted to IFooBar sub-class.

    Check out this tiny example to understand why:

    interface IFoo { }
    class IFooBar : IFoo { }
    class IFooClub : IFoo { }

    class Program
        void DoFoo(ref IFoo param) {
            Random r = new Random();
            if (r.Next() % 2 == 0)
             param = new IFooClub();  
             param = new IFooBar(); 
        void DoFooMagic()
            IFooBar myFoo = new IFooBar();
            DoFoo(ref myFoo); // <-- Error it can be IFooClub too ;o)), 
                              //Need to save as IFoo and check return type