Reputation: 1006
I have a class like "Person"...
public class Person
{
public string Name { get; set; }
public int Id { get; set; }
}
I have a DTO class like
public class DTOAddress
{
public string City{ get; set; }
public string Country{ get; set; }
}
During runtime I need to get 'City' and 'Country' property in Person class. i.e My expected result will be...
public class Person
{
public string Name { get; set; }
public int Id { get; set; }
public string City{ get; set; }
public string Country{ get; set; }
}
At runtime.
Upvotes: 1
Views: 1013
Reputation: 752
Trying to add properties at runtime is a very bad code smell at best (and impossible as worst - I won't say for sure it's definitely utterly impossible).
I recommend you rethink exactly what you're trying to achieve. If you know that it will always add City
and Country
to the class, why can't you just add them at compile-time? Telling us more about the problem in question could help us suggest alternative solutions.
Upvotes: 3
Reputation: 13495
You can try and use an ExpandoObject
to add properties at run time. See this article.
dynamic expando = new ExpandoObject();
expando.Name = "Dude 1";
now the expando
object contains a property Name
with value Dude 1
.
Upvotes: 2
Reputation: 101732
As far as I know this is not possible. Once a class
is compiled you can't change it, it's done. But you can create a new class with new properties at runtime. There is a good information about that in MSDN:
Upvotes: 2