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
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.
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.
To use the data and access functions defined in the class, you need to create objects.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With