In C#, Why Can't a List≪String≫ Object Be Stored in a List≪Object≫ Variable

In C#, why can't a Liststring object be stored in a Listobject variable

Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!

As a side note, I think it would be more significant whether or not you can do the reverse cast:

List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;

I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.

Does anybody know or can test if such a cast is legal in C#?

Variable type Liststring In object, how can I make a List of this object

list2 is a list:

List<ValidDay> list2 = new List<ValidDay>();

But you're trying to set an object to it:

list2 = new ValidDay() { /.../ };

Don't set it to an object, simply add the object to it:

list2.Add(new ValidDay() { /.../ });

Why can't I add a ListT : Interface to a ListListInterface?

If you could, you would be able to write:

List<I> listOfAs = ListOfLists[0];

var B = new B();
listOfAs.Add(B);

Which is obviously forbidden as you cannot add a B instance to a list of A.

This answer by Eric Lippert gives a good similar example with animals instead of As and Bs.

To answer your second question, we'll need to do what you intend to do with ListOfLists, simply enumerate or modify the collection after it has been initialized.

If the idea is just to have a read only collection of I instances:

IEnumerable<I> collectionOfIs = ListOfA.Cast<I>().Concat(ListOfB.Cast<I>());

which works because List implements IEnumerable

Then you can use ToList to materialize the collection and be able to use an indexer:

List<I> listOfIs = collectionOfIs.ToList();

C# convert Listbaseclass to ListDerivedClass

In your GetSensors method, you are creating instances of the base class Sensor. Trying to implicitly cast them to some other derived class is not possible. You should use a generic type parameter in that method and create instances of the actual derived type.

Like so: (notice the where clause and the new constraint of the T parameter)

public static List<T> GetSensors<T>(JToken jToken) where T : Sensor, new()
{
var sensors = new List<T>();

try
{
foreach (var item in jToken)
{
var s = new T();
s.Label = item["lab"].ToString();
s.ActualTemp = item["tf"] != null ? item["tf"].ToString() : "";
s.HighTemp = item["hf"] != null ? item["hf"].ToString() : "";
s.LowTemp = item["lf"] != null ? item["lf"].ToString() : "";

sensors.Add(s);
}
}
catch (Exception)
{
}

return sensors;
}

Now call it like this:

List<IntSensor> iSensors = ParseJsonData.GetSensors<IntSensor>(internalSensorTree);

Generic List of ListT

The problem is that for reasons related to type safety, you cannot treat a List<string> as a List<object>. If you could, this would be possible:

var list = (List<object>)(new List<string>());
list.Add((object)42); // this should never be allowed to compile

What you can do is this:

private List<DateTime> _dateTimes = new List<DateTime>();
private List<String> _strings = new List<String>();

private List<IList> _listOfLists = new List<IList>();

_listOfLists.Add(_dateTimes);
_listOfLists.Add(_strings);

This works because List<T> implements IList. Of course, you have now "forced" the compilation of the code by forfeiting compile-time type safety. In essence you accept that if you do try to add an object of incorrect type to one of the IList instances you will get a runtime exception.

Entity Framework - Code First - Can't Store ListString

Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.

Behaviour of ListString when using in return statement in c#

But, I am unaware why despite of my method returning a List value, why does the compiler throw this error ?

The List<T>.Sort() method doesn't return a List<T>. It's a void method - it sorts the list in place. You need:

a.Sort();
return a;

Basically a method with a void return type can only be used as a standalone statement. You can't use it as an expression to return, or as a method argument etc.

Why can I not return a ListFoo if asked for a ListIFoo?

Your List<Foo> is not a subclass if List<IFoo> because you cannot store an MyOwnFoo object in it, which also happens to be an IFoo implementation. (Liskov substitution principle)

The idea of storing a List<IFoo> instead of a dedicated List<Foo> is OK. If you need casting the list's contents to it's implementation type, this probably means your interface is not appropriate.

Convert a list to a string in C#

Maybe you are trying to do

string combinedString = string.Join( ",", myList.ToArray() );

You can replace "," with what you want to split the elements in the list by.

Edit: As mentioned in the comments you could also do

string combinedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

Understanding C#'s Type converting

You are misunderstanding how generics works in relation to type inheritance. You can cast an object of type FooRef into a reference of type BaseReference<Foo> because FooRef inherits from BaseReference<Foo>. However, you cannot cast a BaseReference<Foo> into a BaseReference<BaseObjWithID> because unlike the types they are using as generic type arguments, those two generic classes have no such connection.

Take the following example:

public class Fruit {}
public class Apple : Fruit {}

Any Apple object can be stored in a Fruit reference because inheritance ensures that the relationship between them checks out:

Fruit f = new Apple();

However, where generics are involved, each time a generic version of a class is created with a different type argument, those versions are all treated as completely different types. For example, while the above implicit casting would work, the following would fail:

List<Fruit> f = new List<Apple>();

List<Fruit> and List<Apple> are completely different classes. There is no direct conversion between them, implicit or explicit.



Related Topics



Leave a reply



Submit