fullstackhero / blazor-starter-kit

Clean Architecture Template for Blazor WebAssembly Built with MudBlazor Components.
MIT License
3.44k stars 727 forks source link

new keyword vs Activator class #443

Open biproberkay opened 1 year ago

biproberkay commented 1 year ago

https://github.com/blazorhero/CleanArchitecture/blob/11f810d97cb66a251dfbee335b581fa9f1d1beab/src/Infrastructure/Repositories/UnitOfWork.cs#L40

biproberkay commented 1 year ago

The new keyword is used to create an instance of a class in C#. It is used to allocate memory for the object and invoke the class constructor to initialize the object.

The Activator class is a class in the System namespace that provides methods for creating instances of types at runtime. It can be used to create an instance of a class by calling the CreateInstance method and passing it the type of the class that you want to create.

Here is an example of how to use the new keyword to create an instance of a class:

class MyClass
{
    public MyClass()
    {
        // Constructor code goes here
    }
}
// Create an instance of MyClass using the new keyword
MyClass instance = new MyClass();

And here is an example of how to use the Activator class to create an instance of a class:

Type type = typeof(MyClass);

// Create an instance of MyClass using the Activator class
object instance = Activator.CreateInstance(type);

There are a few differences between using the new keyword and the Activator class:

Overall, the new keyword is generally simpler and more efficient to use, but the Activator class can be useful in situations where you need more flexibility or don't know the type of the class that you want to create until runtime.