0

Possible Duplicate:
using c# reflection to call a constructor

How to call the constructor of a class from a string variable?

In PHP I can do this:

$myclassName = '\Namespace\MyClass';
$myParameters = array ('param1', 'param2');

$reflection = new \ReflectionClass($myclassName ); 
$myClassInstance = $reflection->newInstanceArgs($myParameters);

As I can do in C #?

i have a list o views like

  • PersonView
  • HouseView
  • CarView

and her ViewModel

  • PersonViewModel
  • HouseViewModel
  • CarViewModel

I have one ObservableCollection in my code i dont wana add a new Command for each kind

AddPersonView = new RelayCommand(() =>
{
  //code
});

AddCarView = new RelayCommand(() =>
{
  //code
});

//etc

i wanna pass CommandParameter to the same Command

AddView = new RelayCommand((name) =>
{
  // pseudo code
  var o = CreateIntance(name + "View");
  o.DataContext = CreateIntance(name + "ViewModel");
  _observableList.Add(o);
  // end 

});
Community
  • 1
  • 1
rkmax
  • 17,633
  • 23
  • 91
  • 176
  • the response in that question (http://stackoverflow.com/q/3255697/816721) is not clear for me – rkmax May 05 '12 at 17:52
  • 2
    Why do you want to do this? In general, anything you have done in PHP is something you don't want to do in C#. – John Saunders May 05 '12 at 17:55
  • I wrote the name of my classes and their methods so that I can leave my code more maintainable – rkmax May 05 '12 at 17:56
  • The keyword is "reflection". I have added the tag. Look at the related questions. –  May 05 '12 at 18:02

1 Answers1

2

You can try Activator.CreateInstance.

Like

Namespace.MyClass obj = (Namespace.MyClass)Activator.CreateInstance(typeof(Namespace.MyClass), new[] { param1, param2});
Mario S
  • 11,715
  • 24
  • 39
  • 47
  • ill try with `var o = System.Activator.CreateInstance(Type.GetType("FullNameSpaceClassName"));` – rkmax May 05 '12 at 19:06