c# - Why creating a variable of a type "IEnumerable<MyClass> myVar" doesn't need a NEW keyword? -
if have written class called myclass , need object of it's type, go
var myvar = new myclass(); and if our myclass has ienumerable interface again need new keyword such as:
class myclass : ienumerable {...} var myvar = new myclass(); what situation when our class, myclass not used 1 type instantiate new variable of say:
ienumerable<myclass> myvar; i should error if go
ienumerable<myclass> myvar = new ienumerable<myclass>(); but trying understand logic behind this. how enumeration set of objects created in situation?
there difference between declaring variable , instantiating object.
ienumerable<myclass> myvar; just declares variable. no instantiation has occurred. if hover on variable debugger, null. line valid:
myclass myvar; you still need instantiate ienumerable derived type use it:
ienumerable<myclass> myvar = new list<myclass>(); note line not compile, because cannot instantiate interface or abstract class.
ienumerable<myclass> myvar = new ienumerable<myclass>(); //does not compile! you seem confused myclass in ienumerable<myclass>. generic type parameter, again, nothing instantiated.
to speak return values, following code totally valid:
ienumerable<myclass> myvar = somefunction(); myvar = new list<myclass>(); however, somefunction need instantiate (or generate via linq) class derives ienumerable, or else assign null again. i'm not sure mean "instantiated , allocated value in 1 step", hard :). functions modularize code, there isn't magic. return valid value, has have 1 in first place or otherwise make 1 itself.
Comments
Post a Comment