0

For example, I want to create a program that records the book title, author, genre, etc., each book is a separate class object, how can I make it so that I can automatically declare new class objects during the program's operation (I need this for educational purposes)

asked Nov 1, 2022 at 18:19
1
  • You can use anonymous types. Commented Nov 1, 2022 at 18:20

1 Answer 1

4

You can use the Activator.CreateInstance method to create a new instance of a given type. This example demonstrates the usage.

class MyType
{
 public override string ToString()
 {
 return "My type.";
 }
}
MyType obj = Activator.CreateInstance<MyType>();
Console.WriteLine(obj);

If you have a type that has constructor parameters, these can be given in the following way:

class MyTypeWithConstructor
{
 string _message;
 public MyTypeWithConstructor(string message)
 {
 _message = message;
 }
 public override string ToString()
 {
 return _message;
 }
}
object[] parameters = new object[1] { "Hello world!" };
MyTypeWithConstructor obj2 = (MyTypeWithConstructor)Activator.CreateInstance(
 typeof(MyTypeWithConstructor), args: parameters);
Console.WriteLine(obj2);
answered Nov 1, 2022 at 18:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.