Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object instance without invoking constructor?

Tags:

c#

In C#, is there a way to instantiate an instance of a class without invoking its constructor?

Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.

NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.

like image 912
Chris Gillum Avatar asked Nov 17 '08 19:11

Chris Gillum


People also ask

Can we create object without calling constructor?

Actually, yes, it is possible to bypass the constructor when you instantiate an object, if you use objenesis to instantiate the object for you. It does bytecode manipulations to achieve this. Deserializing an object will also bypass the constructor. It isn't possible to do this using reflection.

How do I create an instance of a class without a constructor?

Even if you don't have a constructor in your class, you can still create objects. Example: class A{ } class B{ public static void main(String[] args){ A x = new A(); B y = new B(); //both are valid and the code will compile.

How is it possible to create an object of a class without defining a constructor?

The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.

Can we create a dog object without using its constructor?

If we use the third constructor when we create the Dog object the breed and name fields are set to our desired values on one statement. If you omit a constructor, the Java compiler creates one for you internally. That default constructor has no parameters and no code so it really does nothing.


1 Answers

I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.

Remarks from MSDN says:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object.

like image 62
Hallgrim Avatar answered Sep 22 '22 14:09

Hallgrim