How many different ways to create an object of the class?
There are 5 different ways to create an object of the class.
1. By using new() keyword:
Using the 'new()' keyword is the most straightforward approach for creating an object of a class. Consider the following example of a class called Student:
public class Student
{
public Student()
{
//default constructor
}
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public void TakeExam()
{
//some code here
}
}
Now, we create the object by mentioning the class name, followed by the object name, and then utilizing the 'new()' keyword. Subsequently, we use this object 'obj' to invoke the 'TakeExam()' method.
Student obj = new Student();
Obj.TakeExam();
Similarly, you can create multiple objects of the 'Student' class using the same approach.
2- Delegate object creation by DI container:
Delegate object creation by a Dependency Injection (DI) container refers to the process where the responsibility of creating objects is delegated to the DI container instead of creating them explicitly in the code.
In a DI container, you register the types and their dependencies, and the container takes care of resolving and creating instances when they are needed. This decouples the creation and management of objects from the rest of the application, promoting better separation of concerns and improving testability and maintainability.
Here's an example of how you can use a DI container, such as Microsoft's built-in DI container in ASP.NET Core, to delegate object creation:
// Example of a service interface
public interface IMyService
{
void SomeMethod();
}
// Implementation of the service interface
public class MyService : IMyService
{
public void SomeMethod()
{
// Some logic here
}
}
// In the composition root (startup class for ASP.NET Core or Main method)
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register the MyService implementation with the DI container
services.AddTransient();
// Other service registrations if needed
}
}
// In the consuming class (controller, service, etc.)
public class MyController
{
private readonly IMyService _myService;
// Dependency injection through constructor
public MyController(IMyService myService)
{
_myService = myService;
}
public void SomeAction()
{
// Use the _myService instance
_myService.SomeMethod();
}
}
In this example, we use the built-in DI container of ASP.NET Core to register the 'MyService' implementation of 'IMyService'. When the 'MyController' class is constructed, the DI container automatically resolves the dependency and provides the 'IMyService' instance through constructor injection.
By using DI container to delegate object creation, you can take advantage of the container's features, such as managing the object lifetime (transient, scoped, or singleton), handling constructor parameter injection, and managing complex object graphs. This promotes cleaner and more maintainable code, as you can focus on defining dependencies and their lifetimes in one place (composition root) rather than scattered throughout the codebase.
3. Create an object by using reflection:
There are two ways to create instance of the class using refelection:
Student obj = (Student)Activator.CreateInstance(typeof(Student));
obj.TakeExam();
// 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.TakeExam();
4. Get an object from object pool:
Rather than creating new objects each time, we can also retrieve objects from an object pool. To achieve this, we pre-create objects using the new keyword or reflection, ensuring that the object creation happens only once. These pre-created objects are then kept in the pool and reused as needed.
int arraySize = 100000;
//Get an array from the object pool
int[] arr = ArrayPool.Shared.Rent(arraySize);
//Use an array
//some code here
//Return array to pool
ArrayPool.Shared.Return(arr);
5- Creating an object by de-serialize it:
The final approach for object creation involves deserialization. In this scenario, we start with serializing an object into binary, JSON, XML, or any other format. Subsequently, we deserialize the serialized data back into an actual object.
Let's consider an example where we have a 'Student' class and we aim to create an object using deserialization from serialized data.
class Program
{
static void Main()
{
var std = CreateStudentObject();
}
staic Student CreateStudentObject()
{
using FileStream fs = new FileStream("SerializedPerson.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
Student student = (Student)formatter.Deserialize(fs);
return student;
}
}