Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this C# casting example work?

Tags:

c#

.net

casting

I'm trying to understand why this cast doesn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CastTest {

    class Foo {}

    // I want to use this kind of like a typedef, to avoid writing List<Foo> everywhere.
    class FooList : List<Foo> {}

    class Program {
        static void Main(string[] args) {
            FooList list = (FooList) Program.GetFooList();
        }

        // Suppose this is some library method, and i don't have control over the return type
        static List<Foo> GetFooList() {
            return new List<Foo>();
        }
    }
}

This generates a runtime error:

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[CastTest.Foo]' to type 'CastTest.FooList'.

Can anyone explain why this doesn't work, and whether I can get around this somehow?

like image 727
Eric Avatar asked Mar 05 '12 22:03

Eric


People also ask

Why there is no string in C?

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable. A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0' ).

Why is C not A or B?

Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.

What do <> mean in C?

<> in some languages means "does not equal". But in c, the operator is != . Also note the difference between logical AND ( && ) and bitwise AND ( & ). You should use the logical operators for multiple criteria in a conditional statement.

Why array bounds checking is not available in C?

C # in Telugu Languages like Java and python have bounds checking so if you try to access an out of bounds element, they throw an error. C++ design principle was that it shouldn't be slower than the equivalent C code, and C doesn't do array bounds checking.


1 Answers

Just because your FooList is a List doesn't make the List a FooList.

like image 199
Mattias Åslund Avatar answered Sep 30 '22 01:09

Mattias Åslund