Create an object in C # without using a new keyword?

Is there a way to create an object without using a new keyword in C #, for example, class.forname (); in java.

I want to dynamically create a class object. The creation of an object may depend on user input.
I have a base class x and there are 5 subclasses (a, b, c, d, e). My user input will be a or b or ... e. Using this, I need to create an object of this class. How to do it?

+5
source share
5 answers

you can use the activator class .

Type type = typeof(MyClass);
object[] parameters = new object[]{1, "hello", "world" };
object obj = Activator.CreateInstance(type, parameters);
MyClass myClass = obj as MyClass;
+14
source

Do you mean a static class?

static class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Foo.Bar()");
    }
}

Foo.Bar();.

, . " new" - , , . , .

: , , factory, : " . ".

:

static class PizzaFactory
{
    static Pizza CreatePizza(String topping)
    {
        if (topping == "cheese")
        {
            return new CheesePizza();
        }
        else if (topping == "salami")
        {
            return new SalamiPizza();
        }
    }
}

class Pizza { }
class CheesePizza : Pizza { }
class SalamiPizza : Pizza { }

, .

+3

default, :

var s = default(string); // null
var i = default(int);    // integer (0)
0

Activator , -,

0
source

You may be able to do this with

typeof(MyType)
-3
source

All Articles