2

I have a generic method and I want to send to it a type taken from a string variable.

The signature of my generic method is:

public ICollection<TEntity> agregarItems<TEntity>(ComboBox cb) where TEntity : new()

And I want to do this:

Type tipo = Type.GetType("MyNamespace." + cb.Name);

cliente.GetType().GetProperty(cb.Name).SetValue(cliente,
        agregarItems<tipo>(cb), null);

Where cb is a ComboBox object and cliente is an instance of a class.

cb.Name could be "Phone" and the Phone class already exists in MyNamespace.

Because tipo isn't defined formally I get the following error:

The type or namespace name 'tipo' could not be found (are you missing a using directive or an assembly reference?)

I need a workaround that let me send a not formally defined type to the generic method.

Marc
  • 3,905
  • 4
  • 21
  • 37
  • 1
    It is impossible (or very hard), but, maybe, there are another workaround to achieve your goal. What is your goal? – Hamlet Hakobyan Feb 06 '13 at 07:40
  • +1 to @HamletHakobyan. The type you send to the generic method, needs to be a constant at compiletime. That is: you cannot parse it an objectreference. – Jens Kloster Feb 06 '13 at 08:08

2 Answers2

0
Type tipo = Type.GetType("TypeName");

only works for very basic types.

The types you want to reference might be in an assembly like System.Web, System, etc. It is not sufficient that this assembly is referenced, you also need to tell the runtime in which assembly your type is.

So try

Type tipo = Type.GetType(YourType.AssemblyQualifiedName);

instead of

Type tipo = Type.GetType(YourType.FullName);

Additionally, you are using a runtime determined type (tipo) to create a compile-time determined generic overload. That cannot work - ever.

You need to modify the generic method to pass the type as argument.

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • Thanks. I read about AssemblyQualifiedName but I can't see how to use the value of the string variable. The value could be "Email", "Phone", etc. For sure I am not understanding it right. –  Feb 06 '13 at 08:37
  • The type to be send to the generic method is based on the combobox's name. –  Feb 06 '13 at 08:42
  • Probably the combobox's selected item name. So you need to create a class for your comobox-items with fields type and text, and override the tostring method of this class, then you can access the combobox selected item's qualified name (or rather the type directly). And then agregarItems needs to return an object, because it cannot be generic. So you have to set the corresponding type in the place where you populate your combobox items. – Stefan Steiger Feb 06 '13 at 08:47
0

What you have to do is to create the instance with the type you obtained in the way presented here (with an Activator):

How to dynamically create generic C# object using reflection?

Community
  • 1
  • 1
dutzu
  • 3,883
  • 13
  • 19