In C#, the out
keyword can be used in two different ways.
As a parameter modifier in which an argument is passed by reference
class OutExample { static void Method(out int i) { i = 44; } static void Main() { int value; Method(out value); // value is now 44 } }
As a type parameter modifier to specify covariance.
// Covariant interface. interface ICovariant<out R> { } // Extending covariant interface. interface IExtCovariant<out R> : ICovariant<R> { } // Implementing covariant interface. class Sample<R> : ICovariant<R> { } class Program { static void Test() { ICovariant<Object> iobj = new Sample<Object>(); ICovariant<String> istr = new Sample<String>(); // You can assign istr to iobj because // the ICovariant interface is covariant. iobj = istr; } }
My question is: why?
To a beginner, the connection between the two doesn't seem intuitive. The use with generics doesn't seem to have anything to do with passing by reference.
I first learned what out
was in relation to passing arguments by reference, and this hindered my understanding of the use of defining covariance with generics.
Is there a connection between these uses that I'm missing?
System.Func<in T, out TResult>
delegate.