Can you create an object without using new operator in C#?
Yes, by using 'Activator' class we can create object of the class. For this we need to add reference of 'system.Reflection'.
ClassName obj = (ClassName )Activator.CreateInstance(typeof(ClassName ));
The 'CreateInstance' method of the Activator class generates an instance of the specified type by invoking the constructor that best matches the provided parameters. If no parameters are provided, it invokes the constructor with no parameters, commonly known as the parameterless constructor.
The 'Activator' class offers two methods to create class instances: 'CreateInstance' and 'CreateInstanceFrom'. For instance, if we have a class called 'Student', we can create an object of the Student class using 'Activator', as shown below:
Approach 1:
void createObjectWithoutNew1()
{
Student obj = (Student)Activator.CreateInstance(typeof(Student));
obj.TakeEaxam();
}
Approach 2:
void createObjectWithoutNew2()
{
// Create an instance of the Student class that is defined in this assembly.
System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, typeof(Student).FullName);
// Call an instance method defined by the Student type using this object.
Student st = (Student)oh.Unwrap();
st.TakeEaxam();
}