0

What i need to do is something like this, but really can't understand how.

 Object value = new typeof(i.FieldType.GetType());

The type of the value can be whatever, it just must be inherit of a class (for example, BaseClass). The type will be read from (.Net) System.Reflections. But i don't know how can i create a new object of this.

How can i create a new() object (constructor), of an object stored as Object, of which the type if known by the System.Reflections?

9
  • 2
    It sounds to me like you need a Factory method. See en.wikipedia.org/wiki/Factory_method_pattern Commented Jul 12, 2015 at 15:25
  • I guess this might help : stackoverflow.com/questions/6472980/… ? Commented Jul 12, 2015 at 15:27
  • Unless you're writing something specialistic, a generic application doesn't need reflection. Using base classes, interfaces and perhaps a factory as suggested by @Robert you should be fine. Explain how you would use this code later. Commented Jul 12, 2015 at 15:27
  • 2
    BaseClass value = (BaseClass)Activator.CreateInstance(typeof(t)) Commented Jul 12, 2015 at 15:31
  • @OlivierJacot-Descombes That will only work if he doesn't want access to the inherited class's members. Commented Jul 12, 2015 at 15:34

3 Answers 3

1

You can use ConstructorInfo class

 var constructorInfo = typeof(myclasstype).GetConstructor();
 if (constructorInfo != null)
 {
     var myclass = constructorInfo.Invoke();
 }
Sign up to request clarification or add additional context in comments.

1 Comment

That's probably the hard way to do it. See Oliver's comment below the question.
1

Do you really need to construct the type at all? If you want to convert a string to a type dynamically (according to one of your comments), then all you need is the System.Convert.ChangeType method.

object convertedValue = Convert.ChangeType(stringValue, i.FieldType.GetType());

Where the second argument to ChangeType is a System.Type.


The Activator is really only needed, if you want to create new (empty) objects dynamically. If the field types you are talking about are standard types like string, int, or bool, then Convert.ChangeType will do it.

Comments

0

You are searching for Activator.CreateInstance(Type type)

Comments

Your Answer

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.