I have a class
Class account {
Int id ;
}
I want change it on the run to
Class account {
Int id;
String Name;
}
And I want to make a object of newly modified class
Is this possible, it would be really helpful
I have a class
Class account {
Int id ;
}
I want change it on the run to
Class account {
Int id;
String Name;
}
And I want to make a object of newly modified class
Is this possible, it would be really helpful
Im not to say that it is impossible, but i would think it is not. Instead you can use Entity Composition like so
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Account a = new Account();
a.Add("My name is John");
a.Add(10);
Console.WriteLine(a.Get<int>(typeof(int)));
Console.WriteLine(a.Get<string>(typeof(string)));
Console.ReadLine();
}
}
class Account
{
private Dictionary<Type, object> _fields = new Dictionary<Type, object>();
public void Add(object data)
{
_fields.Add(data.GetType(), data);
}
public void Remove(Type type)
{
_fields.Remove(type);
}
public T Get<T>(Type type)
{
object data = null;
if (_fields.TryGetValue(type, out data))
{
return (T)data;
}
return default(T);
}
}
}
You can add any class and retrieve it again. I recommend using a wrapper class even for the simplest fields, otherwise you may prevent yourself from adding more fields of type string. For example you cannot add both a name and a surname, you will have to wrap them in a Name and Surname class. Now if you want to do this during runtime, you will have to also look into using a component framework such as MEF
It seems like it's not possible. However, you could use a different approach:
var account = new Dictionary<string, object>();
account["id"] = 42;
account["name"] = "my name";
Which will probably be more performance-friendly rather than trying to add another field.
Following @LuqJensen answer, who would have issues if adding, for example, two strings, you could as well do:
class Account
{
private Dictionary<string, object> _fields = new Dictionary<Type, object>();
public void Set(string name, object data)
{
_fields[name] = data;
}
public T Get<T>(string name)
{
object data = null;
if (_fields.TryGetValue(type, out data))
return (T)data;
return default(T);
}
}
If you really need to do this, and I'll always advise against it, you could use the System.Dynamic
namespace like so:
dynamic obj = new System.Dynamic.ExpandoObject();
obj.id = 100;
obj.Name = "Something";
Keeping in mind of course that everything that the compiler does on your behalf to keep your code functional, now has to be done at run time.