Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an instance from a string in C#?

Tags:

c#

reflection

I'm reading information from an XML which contains the type of an object that I need to instantiate along with it's constructor parameters.

The object type is actually in another project, within a sibling namespace. (I need to create a Company.Project2.Type within Company.Project1 class.)

I found this question, but it doesn't handle the constructor parameters or the fact that it's in another namespace.

How can I do this?

Edit: The assembly name and default namespace wasn't set correctly in the project properties.

like image 819
Ben S Avatar asked Mar 15 '09 17:03

Ben S


People also ask

How do I create an instance of a string?

By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.

What is $@ in C#?

C# also allows verbatim string interpolation, for example across multiple lines, using the $@ or @$ syntax. To interpret escape sequences literally, use a verbatim string literal. An interpolated verbatim string starts with the $ character followed by the @ character.

Are strings objects in C#?

Example: Create string in C# Note: A string variable in C# is not of primitive types like int , char , etc. Instead, it is an object of the String class.

What is instance in c3?

An instance field, in C#, is a variable of any type contained within a class or struct, and is used to store object data. It is a member of its containing type with one copy of the field for each instance of the containing type.


1 Answers

  • You need to specify the full type name to Type.GetType(), including namespace, e.g. "Company.Project2.Type"
  • If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly Company.Project2.dll, you might specify "Company.Project2.Type, Company.Project2".
  • To call a constructor with parameters you can call Activator.CreateInstance(Type, Object[]) or get the exact constructor you want with Type.GetConstructor() and then call ConstructorInfo.Invoke().

If that doesn't help, please give more information.

like image 138
Jon Skeet Avatar answered Oct 07 '22 01:10

Jon Skeet