5

is it possible to initialize a class by a string variable? I have code in PHP.

<?php
  $classname = "test";

  $oTest = new $classname();

  class test{
  }
?>

how do I do this in c#?

1
  • I think JaredPar answers your question, however why do you need this? What are you trying to solve? Commented Aug 9, 2009 at 21:49

3 Answers 3

19
System.Activator.CreateInstance(Type.GetType(className))

The problem, however, is that C# 3.0 is a statically typed language. You can't just call random methods on the returned object. You can have the classes you might instantiate implement some common interface and cast the result of the above expression to the interface or manually use reflection to call methods on the returned object.

Sign up to request clarification or add additional context in comments.

3 Comments

Seeing the answer helped me understand the question. +1
What do you mean by "C#, as of Version 3.0 is a statically typed language". That suggests it only recently became a statically typed language. It always has been. In C# 4.0 there is the new dynamic keyword which means that C# will get some aspects of dynamic languages if desired.
Colin: I might have worded it ambiguously. Fixed.
5

You can use the Activator.CreateInstance method to achieve a similar result. But you will have to provide the assembly name in addition to the fully qualified name of the type

var instance = Activator.CreateInstance("SomeAssemblyName","Some.Full.Type.Test");

Comments

1

You can use Activator.CreateInstance. The documentation for the various overloads is here: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.