Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object assignment in C#

This is something I encountered while using the C# IList collections

IList<MyClass> foo = new List<MyClass>();
var bar = new List<MyClass>();

foo.AddRange() // doesn't compile
bar.AddRange() // compile

As far as I know, in C# (on the contrary of C++) when we create an object with this syntax, the object type get the right side (assignment) and not the left one (declaration).

Do I miss something here !

EDIT

I still don't get it, even after your answers, foo and bar have the same type ! enter image description here

like image 820
Wassim AZIRAR Avatar asked Nov 22 '13 15:11

Wassim AZIRAR


1 Answers

There's nothing so subtle going on here:

  • foo has the type IList<MyClass> and IList<T> doesn't have an AddRange method
  • bar has the type List<MyClass> and List<T> does have an AddRange method.

That's all. It would be just the same in C++.

Update: In the edited-in addition, you're calling GetType(), which gets the run-time type of the object - at compile time the compiler is looking at the static type of the foo and bar variables.

Thinking about Object myObj = "MyString" might make things clearer, because there is a more obvious difference between an 'Object' and a 'String', even though they have the same inheritance relationship as IList and List

like image 161
Will Dean Avatar answered Oct 04 '22 23:10

Will Dean