1) I read some (general) code snippet and saw some places that used IList<T>
and some used IEnumerable
. What is the pros to use the first over the latter?
2) is
and as
in c#.
I understand is
does type check and as
does casting.
But what is exactly casting? forcing data to some sized object? when is
and as
differ?
A IList[<T>]
represents something that:
An IEnumerable
, on the other hand, can only be iterated. Not all things that can be iterated are lists. For example:
static IEnumerable<int> Get() {
Random rand = new Random();
while(true) yield return rand.Next();
}
that ^^^ is an infinite sequence. It has no length, cannot be mutated, cannot be accessed by index... however, it can be iterated:
foreach(int i in Get().Take(200)) {
Console.WriteLine(i);
}
is
performs a type check that returns true
/false
... i.e. is obj
an IList
? yes or no.
as
performs a "try to do this" type-check; it returns null
if it fails, or a typed reference (etc) if it is successful. Basically, it is an efficiency thing:
if(obj is IList) {
var list = (IList) obj;
...
}
is less efficient than:
var list = obj as IList;
if(list != null) {
...
}
they also behave differently if obj
is null; is
throws an exception; as
returns null
.
IList
offers certain methods that IEnumerable
doesn't. Most importantly, the ability to add to it (for more information, check out the msdn)is
compares types, returning if a certain object can be casted to a type. as
actually performs that cast, returning null
if it failed. Casting means converting an object of type A
to an object of type B
, for whatever reason.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With