Reputation: 97
I have been asked this question in a job interview, but not sure what are the other options available in C# to create an object of a class. I know the basic way to create an object. For example: I have a class with name 'ClassName', so to create the object, I can use
ClassName classNameObject = new ClassName();
Can someone please tell me what are other ways which can be used to instantiate a class? Thanks in advance!
Upvotes: 3
Views: 1133
Reputation: 9646
There are several more ways:
Create an object using reflection.
object classNameObject = Activator.CreateInstance(typeof(ClassName));
The
CreateInstance<T>()
generic method is used by compilers to implement the instantiation of types specified by type parameters.
See more about it here.
Create a reference to an existing object.
ClassName classNameObject = new();
ClassName otherClassNameObject = classNameObject;
Create an object using DI (dependency injection) containers by registering an instance (I will not write here the code as it depends on which DI you use).
Create an object with deserializing.
BinaryFormatter formatter = new();
(ClassName)formatter.Deserialize(...);
You may also use JsonConvert.DeserializeObject<ClassName>
.
Create an object with MemberwiseClone.
ClassName classNameObject = new();
ClassName otherClassNameObject = (ClassName) this.MemberwiseClone();
Note, there are also many ways of different usages of new
keyword but I didn't mention it here as it is just syntax.
Upvotes: 4