is it possible to initialize a class by a string variable? my syntax is bellow:
string sClassContainer="
class a
{
Property1;
Property2;
}"
how do I do this in c#?
is it possible to initialize a class by a string variable? my syntax is bellow:
string sClassContainer="
class a
{
Property1;
Property2;
}"
how do I do this in c#?
Yes you can, but it would be nearly useless. Even with older .NET versions you could use How to programmatically compile code using C# compiler... But then? You can use it only through reflection (technically, if your "new" class implements an interface or override some virtual methods of a base class, you can then create it through reflection and use it through the interface/base class)
See here for a complete example Is it possible to dynamically compile and execute C# code fragments?
I'll add that in C# 4.0 you can use dynamic
to create "dynamic" "classes".
dynamic myObj = new ExpandoObject();
myObj.Prop1 = "Hello";
myObj["Prop2"] = "World. Today is ";
string myPropName = "Prop3";
myObj[myPropName] = DateTime.Now;
(as noted by SaeedAmiri with dynamic
I'm not creating a class, I'm creating a dynamic object. In this case "class" would mean Duck Typing "classes". So if you create a dynamic object that has a field WalkLikeADuck
, then anyone that needs WalkLikeADuck
can use it even if the object isn't really a Duck
)