1

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#?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
shamim
  • 6,640
  • 20
  • 85
  • 151
  • What format is the string in? You probably have no other choice but to parse it and create a class on the fly. Is the class definition already known? – SliverNinja - MSFT Oct 27 '11 at 06:26
  • Do you mean you want to somehow instantiate the class "a", which is defined in the string "sClassContainer"? Something likethis?: `var instanceOfA = MyClassGenerator.CreateInstance(sClassContainer);` I think I understand what you're asking, but not whether it is possible. – Kjartan Oct 27 '11 at 06:37
  • 1
    What exactly is the purpose of this code? If you have some specific task to solve, maybe there is some other easier way to accomplish it. – Kjartan Oct 27 '11 at 06:44

1 Answers1

0

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)

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • In your example you create an specific object, not specific type. – Saeed Amiri Oct 27 '11 at 06:37
  • @SaeedAmiri I consider it to be Duck Typing. `When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.` (http://en.wikipedia.org/wiki/Duck_typing). – xanatos Oct 27 '11 at 06:41
  • :))) very interesting I never heard that :))). but I think it's not so, because type can be used too many times, if sample is what the OP wants (in fact) you are right, but otherwise it's not a duck :) – Saeed Amiri Oct 27 '11 at 06:47