0

This code works:

public void MyMethod()
{
    List<Class> classList= new List<Class>();
    classList.Add(new Class { "set properties" });
}

But what about the code below, when the object (aclass) is filled and comes from the outside of the MyMethod:

public void MyMethod()
{
    List<Class> classList= new List<Class>();
    Class class = (Class)aclass       // "aclass : of type Object"
    classList.Add(class);
} 

All the items in the list will be the same, as the last item. But I want to add another objects to the list and then use them in another place.

Mohsen
  • 323
  • 1
  • 6
  • 15
  • How does it "not work"? Does it throw a `System.InvalidCastException`? – Andrew Shepherd Apr 24 '17 at 06:16
  • it works. But "All the items in the list will be the same, as the last item." I want to add another objects to the list. – Mohsen Apr 24 '17 at 06:17
  • The `aclass` is not of `object` type and your code is not relevant for the problem – Gilad Green Apr 24 '17 at 06:18
  • change variable name and type casting should be same i.e aclass should typeof(Class) – Zahid Mustafa Apr 24 '17 at 06:21
  • 1
    You need to create a new object for each element in the list you want to add. You are just adding the same object over and over, and that object is a reference type, so modifications to that object are reflected in each reference to the object, i.e. each element in the list. See marked duplicates for additional info. – Peter Duniho Apr 24 '17 at 06:28
  • Each time, it is filled with new properties, but all items in the list have the the last properties of the object. – Mohsen Apr 24 '17 at 06:31
  • 1
    _" it is filled with new properties"_ -- there is no such thing as "filling with new properties". You haven't bothered to include a good [mcve], but it seems clear enough that your "fill with new properties" is just code that assigns new values to the properties of an existing object. You've only called `new Class()` once, assigned that to `aclass` and/or `class`, and then repeatedly changed the property values before adding the object to the list. You can't do that. You have to call `new Class()` for each new object you want to add to the list. – Peter Duniho Apr 24 '17 at 15:32
  • @PeterDuniho Thank you for your attention. – Mohsen Apr 24 '17 at 15:57

1 Answers1

-1

Here is Simple way to do so

List<Class> classList= new List<Class>();

if(aclass = typeof(Class)){
 classList.Add(aclass);
}