Reputation: 533
I have an object created from the class "object" and it contains a list I have created. The list is a collection of objects created from a class called "MyClass". And, that class contains two string properties.
public Class MyClass
{
private string _propOne;
public string PropOne
{
get {return _propOne;}
set {_propOne=Value;}
}
private string _propTwo;
public string PropTwo
{
get {return _propTwo;}
set {_propTwo=Value;}
}
}
I have a method which returns an object of the class "object"
private object GetData()
{
// It converts the list created to an object created from the class "object"
}
Then I call the method like in the following.
object temp=GetData();
Now I want to iterate over "temp" and assign it to another list created from the objects of the class "MyClass".
private List<MyClass> _anotherCollection;
public List<MyClass> AnotherCollection
{
get {return _anotherCollection;}
set {_anotherCollection=Value;}
}
........................
foreach (var a in temp.GetType().GetProperties())
{
object firstParam = "PropOne";
object secondParam = "PropTwo";
AnotherCollection.Add(new MyClass() { PropOne = a.GetValue(firstParam), PropTwo = a.GetValue(PropTwo) });
}
But it gives me the following compilation error.
Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
Can someone help me to fix it ?
Upvotes: 0
Views: 54
Reputation: 156948
You have to cast the returned object from GetValue
to a string
. The compiler doesn't know that the object
returned from GetValue
is actually a string
, so you have to tell it that like this.
Also, you have to pass in the instance you are trying to get the value for (temp
in this case):
PropOne = (string)a.GetValue(temp)
Upvotes: 2