Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize a class by string variable in c#?

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

like image 203
Moon Avatar asked Aug 09 '09 21:08

Moon


People also ask

How do you initialize a string variable?

To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).

How do you declare a string variable in C?

Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.

Can you initialize string?

Initialize a string by passing a literal, quoted character array as an argument to the constructor. Initialize a string using the equal sign (=). Use one string to initialize another. These are the simplest forms of string initialization, but variations offer more flexibility and control.


1 Answers

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.

like image 94
mmx Avatar answered Oct 19 '22 03:10

mmx