blazor-starter-kit icon indicating copy to clipboard operation
blazor-starter-kit copied to clipboard

new keyword vs Activator class

Open biproberkay opened this issue 3 years ago • 1 comments

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

biproberkay avatar Dec 20 '22 10:12 biproberkay

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:

  • The new keyword can only be used to create an instance of a class that is known at compile-time, while the Activator class can be used to create an instance of a class that is not known until runtime.
  • The Activator class can be used to create an instance of a class that is located in another assembly, while the new keyword can only be used to create an instance of a class that is located in the current assembly.

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.

biproberkay avatar Dec 20 '22 11:12 biproberkay