Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can we create object without using constructor
Posted

1 solution

That depends on what you are constructing!

If its a reference type instance - a class - then basically, no: if you don't provide a constructor then the system will create an empty default constructor for you. And a constructor will always be called when you use the new keyword - and you do that every time you create a reference type instance because that is the only way to get a "fresh" instance.
C#
MyClass mc;
Does not call the MyClass constructor, because it doesn't create an instance of the class, just a variable that can hold a reference to the instance when it is created later.
C#
MyClass mc = new MyClass();
Always calls a constructor as it does create an instance.

If it's a value type - an basic type such as int, double, bool, or a struct - then you don't need to cretae or call a constructor. Just creating the instance is sufficient:
C#
int i = 42;
MyStruct ms;
These both create value type instances, without calling a constructor. You can call a constructor for a value type by using the new keyword:
C#
MyStruct ms = new MyStruct();
But you don't have to do it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900