maybe I'm not clever enough, but...
I have a freshly created anonymous object and wanna cast it to a special class.
I tried something like:
- () convert:
SomeClass casted = (ClassName) obj - as type:
SomeClass casted = obj as ClassName
The last idea I found online was to cast via each property:
https://dotnetfiddle.net/bU8gwE (by method: CastTo<T>(object))
But nothing worked. :(
Here is my object:
var test = new { FieldOne = "test2", FieldTwo = 2 };
And here is my type, it's an own class:
public class SomeClass
{
public string FieldOne;
public int FieldTwo;
}
So how to cast obj in type SomeClass?
I'm happy for every advise.
First and primarily, a general advice: do not use empty catch clauses in your
try-catchconstructs (with the exception of so-called vexing exceptions, but i digress). If you try your hardest to ignore and discard any exception your code throws unseen, you will have a very hard time knowing what's going wrong with your code.If you were to print out any caught exception instead of silently discarding it, the exception would tell you what is going wrong with your code (i.e., what needs to be fixed in your code).
Anyways, with this line:
you are trying to obtain a property info from your CodeRecord class (tmp is an instance of CodeRecord). Now, look at your CodeRecord class. There are no properties defined in CodeRecord, only fields. If you want to populate the fields in CodeRecord through reflection, you will need to get a
FieldInfoand not aPropertyInfo:Some unrelated observation:
What the heck is
Activator.CreateInstance(Type.GetType(typeof(T).ToString()))??? You have the type object for T viatypeof(T). You then get its name string. With its name string you try to find the type object of T again which you already had withtypeof(T). I don't know what that is, but me thinks you need some sleep ;-P You could just have usedActivator.CreateInstance(typeof(T)). Well, hold on, i take that back, you could just have usedActivator.CreateInstance<T>().