-1

I am in the early stages of learning c# and am currently "fixing" a project (as an exercise).

I've come across this code but I can't make sense of it.

List<CartLine> cartList = Lines as List<CartLine>;

Up to now my usage of Lists has been pretty standard

List<T> newList = new List<T>

And similar constructions.

I'm mostly hung up on where "new" keyword went and what "as" is really doing here. Is there another way of writing the above code that I may be more familiar with (to wrap my head around)?

FYI "CartLine" is a class:

    {
        public int OrderLineId { get; set; }
        public Product Product { get; set; }
        public int Quantity { get; set; }
    }

and Lines is linked by the IEnumerable

public IEnumerable<CartLine> Lines => GetCartLineList();

Sorry if this is a bit obvious for many of you. I read up on the MS Documentation of AS, but still a bit lost and i can't get great search results regarding its usage.

3
  • 2
    Does this answer your question? When should you use the as keyword in C# Apr 18, 2020 at 13:55
  • Lines is declared as an IEnumerable of CartLine. This means it is a list of things that can be iterated, but it is not necessarily and instance of List<CartLine>. To use the instance as an actual List it needs to be cast. That is what the as is doing here. It is doing a safe cast to a List<CartLine> type to tell the code that it actually is a list. Whether or not this is a good idea in this case is not easy to determine from the code.
    – musicfuel
    Apr 18, 2020 at 13:59
  • as tries to cast whatever it is handed to the given type. Lets say I have a class Lion: Animal. Now I can do Animal myAnimal = new Lion();. But now I can't use any specific Lion stuff on myAnimal so I could do Lion myLion = myAnimal as Lion;, and now I have the same object but I can use it as a Lion. Note here that it tries to cast. If the cast is not valid (because the object is not of that type) it'll return null.
    – user10608418
    Apr 18, 2020 at 14:00

2 Answers 2

1

The as keyword is used to do a cast which is where you treat a variable of one type to act like a different type. From your source it seems the writer wanted to cast IEnumerable to List so they could use the properties of List. Following from this question, enumerable.ToList(); seems more appropriate than a cast.

using System.Linq; // At the top of the file

List<CartLine> cartList = Lines.ToList();
1

In C# 'as' is used to do a safe cast. If an object can't be casted to the desired type it returns null.

Linq IEnumerable.ToList() inserts all elements of an Enumerable<T> in a new List<T>. Only the List will be a new object, single elements will be the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.