0

I am reading a app.config entry

  <add key="ClassNameSpace.ClassName" value="http://xxxx/xxx.asmx"/>     

And I am trying to get the type for the key

  var section = configuration.GetSection(sectionKey.ToString());
  var appSettings = section as AppSettingsSection;
  if (appSettings == null) continue;

  foreach (var key in appSettings.Settings.AllKeys)
  {
      System.Type type = System.Type.GetType(typeof(key).AssemblyQualifiedName);
      var webService = new SecureWebService<type>().Service;
  }

But I am getting below error

'key' is a variable but is used like a type

Any idea to solve this issue

user1104946
  • 680
  • 1
  • 9
  • 30
  • 3
    You can not call `typeof` with a variable, you need to call it with a Type (thats what the warning is trying to tell you) typeof(int) would be valid. You can call GetType with the key to get a type instance. – quadroid Sep 19 '19 at 05:48
  • Nobody ever reads exception messages :( _"'key' is a variable but is used like a type"_ means that `key` is a variable, but you use it like a type in `typeof(key)` – vasily.sib Sep 19 '19 at 05:50
  • what is the type of this "appSettings.Settings.AllKeys" – Ajay Kumar Oad Sep 19 '19 at 05:51
  • 1
    The type of that key is probably just "String". I think you want the value of that key to get the new type – Hans Kesting Sep 19 '19 at 05:55
  • So your question is how to get Type by class name? https://stackoverflow.com/questions/11107536/convert-string-to-type-in-c-sharp – TimChang Sep 19 '19 at 06:02

2 Answers2

1

typeof() returns the Type of a type (class, interface, struct...) in the sense of the type name used in the code text.

For a string representation of a type, you should use:

Type type = Type.GetType(key); // full qualified like "namespace.type"
var webService = Activator.CreateInstance(type); // default constructor
  • That would not return what the OP wants, it would return the type of the key name container, not the type name the key represents. `Type.GetType(key.ToString())` is more likely to yield the desired result. – fredrik Sep 19 '19 at 05:56
  • my guess is that OP wants to get `Type` by it's name. Like `"System.String"` -> `typeos(System.String)`, so just leave `System.Type.GetType(key)` – vasily.sib Sep 19 '19 at 05:57
  • Indeed, key.GetType() returns "System.String". I updated the answer. –  Sep 19 '19 at 08:09
0

GetType() returns a System.Typeobject of an object. typeof() returns a System.Type object of a datatype.

var section = configuration.GetSection(sectionKey.ToString());
var appSettings = section as AppSettingsSection;
if (appSettings == null) continue;

foreach (var key in appSettings.Settings.AllKeys)
{
    System.Type type = key.GetType();
    var webService = new SecureWebService<type>().Service;
}
Stefan
  • 652
  • 5
  • 19