Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a object in C# without the use of new Keyword? [closed]

Is there a way to create a object without the use of new keyword in C# some thing like class.forname(); in java.

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

like image 214
Abhay Kumar Avatar asked Nov 08 '11 10:11

Abhay Kumar


People also ask

How do you create an object in C?

In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.

Can we create an object in C?

In C we instantiate an object like this: EmployeePtr employee = (EmployeePtr) malloc (sizeof(EmployeeStr)); The employee variable is a pointer type to an EmployeeStr that will be created in the heap. malloc() returns a void pointer (one with no specific type) so you need to cast it to the EmployeePrt type for safety.

Why do we create object in C?

To use the data and access functions defined in the class, you need to create objects.

How do you create an object?

Creating an Object So basically, an object is created from a class. In Java, the new keyword is used to create new objects. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object.


2 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;
like image 82
Kralizek Avatar answered Oct 29 '22 21:10

Kralizek


Do you mean a static class?

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

You can then call Foo.Bar();.

But you'd better explain what you're trying to do. "Creating an object without the use of new" is a solution you came up with for a problem you're having. Just explaining that problem might reveal an easier way to solve it.

Edit: you seem to need a factory, given your comment "I want to dynamically create a object of a class. The object creation may depend on the users input".

So something like this may be sufficient:

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 { }

Throwing in an Interface or Abstract class where necessary.

like image 37
CodeCaster Avatar answered Oct 29 '22 23:10

CodeCaster