Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# reference understanding?

if i have :

   public class A {   public int a1;}
   public class B : A {  public int b1;}

   void myFunc(A a) 
   {}

  static void Main(string[] args)
       {
         B b = new B();
         myFunc(b);
       }

in myFunc , a can access b object but it can reference only (without cast) to a region in memory which is type A.

that is understood.

HOwever in covariance it seems that a can also access b : enter image description here

As you can see - it accepts Enumerable of A and it still can access its B typed objects


questions:

1) Ok, How behind the scenes it is working ? how can an A reference can show me a larger object ?

2) What if i wanted to see in the function the a1 property from the A class ?what should I change ?

edit

covariance related:

Before C# 4, you couldn't pass in List: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'

Covariance and contravariance real world example

like image 682
Royi Namir Avatar asked Dec 22 '22 02:12

Royi Namir


1 Answers

How can an A reference can show me a larger object?

First off, it is a smaller type. Every giraffe is an animal but not every animal is a giraffe. Therefore there are fewer giraffes in the world than there are animals in the world. Therefore giraffe is a smaller type than animal.

Your type B is a smaller type than A. And of course a reference to a larger type can refer to something of a smaller type.

That has nothing to do with covariance. It is always the case that an IEnumerable<A> can give you a B:

List<A> myList = new List<A>() { new B(); } // No covariance here
Console.WriteLine(myList[0].GetType()); // it's a B.

A list of animals can contain a giraffe. That has nothing to do with covariance.

Similarly, a reference can always give you a smaller type back:

A a = new B(); // Legal!

to those who says it has nothing to do with covariance...

That a sequence of A can contain a B has nothing to do with covariance. What has to do with covariance is that a sequence of B can be converted to a sequence of A by reference conversion. Before covariant conversions were added to C# 4, that conversion would have failed.

What if i wanted to see in the function the a1 property from the A class? what should I change?

You shouldn't change anything; it already works. Try it.

like image 171
Eric Lippert Avatar answered Dec 24 '22 00:12

Eric Lippert