I see 3 questions here:
1. I want to create a class that looks like this: Is there any way to do this ?
class DynamicClass
{
int EmployeeID,
String EmployeeName,
String Designation
}
Yes, this is possible but the purpose should not be to make a class look like something but to work, behave and hold the data like this. And this is achievable whiteout using CodeGeneration
, "T4 Template
, dynamic
, ExpandoObject
, CSharpProvider
or AnonymousObject
.
2. I want this to be generated at runtime.
Generating a class
at runtime won't do anything if it doesn't create a instance
object.
And if I understand you are trying to save Employee
data where the size of List<Field>
is unbound and the best you can think of is to generate a class
to hold that unbounded data dynamically at runtime.
Creating DynamicEntity
If that is your issue you can attempt to create Employee
as a Entity
like below called as DynamicEntity
where the properties are available as a Dictionary<string,object>
so it can be extended with new attributes/fields without the need of a new class
design and it's not limited to 2-3 fields for employee.
public class DynamicEntity
{
public string Name {get;private set;}
public Dictionary<string,object> Attributes;
public DynamicEntity(string name)
{
Name = name;
Attributes = new Dictionary<string,object>();
Attributes.Add("LogicalName",name);
Attributes.Add("Id",Guid.NewGuid());
}
public object this[string key]
{
get {
return Attributes[key];
}
set{
Attributes[key] = value;
}
}
public void AddAttribute<T>(string attributeName,T data)
{
Attributes.Add(attributeName,data);
}
public void SetAttributeValue<T>(string attributeName,T data)
{
Attributes[attributeName] = data;
}
public T GetAttributeValue<T>(string attributeName)
{
return (T)Attributes[attributeName];
}
}
To use you can create an object at runtime and read/write/append attributes to it.
var u = new DynamicEntity("employee"); //new object
u.AddAttribute<int>("EmployeeID",10); //Add Id
u["EmployeeName"]= "vinod"; //Add Name
u["Designation"] = "hacker"; //Add Designation
u.AddAttribute<string>("Address","India"); //Add New Attribute
u.SetAttributeValue<string>("EmployeeName","Vinod Srivastav");
var id = u.GetAttributeValue<int>("EmployeeID"); //Read Attribute
If everything goes well you can get a object like follows:
System.ServiceModel.ChannelFactory<MyDynamicInterface>
– Damnationclass
if you sayanonymous object
that makes some sense. But what is the purpose of a dynamic class here, i mean what are you attempting to achieve ? Plz see my answer ofDynamicEntity
here https://mcmap.net/q/108799/-how-to-dynamically-create-a-class – Filterable