How to convert a string to a variable reference?

I need to add many public folders from the configuration file. the names are very long, but it all ends with the words "Name", "Domain", "Username" and "Password".

Example:

AddSharedFolder(
  myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryName,
  myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryDomain,
  myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryUsername,
  myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryPassword);

My idea was to call him

AddSharedFolder(
  "myConfigurationHandler.MyConfiguration.MyService.RSController.repository");

Then you have the overloaded AddSharedFolders method:

private static void AddSharedFolder(string prefix)
{
   AddSharedFolder(prefix + "Name", prefix + "Domain", prefix + "Username", prefix + "Password");
}

Obviously, the latter method is incorrect. But how to convert a string to a variable name? Or is it really a stupid programming practice?

+3
source share
4 answers

In C # there is no way to do Eval ("..."), the language is not dynamic. Therefore, your last attempt to the method will not work.

I will go for

var ctr = myConfigurationHandler.MyConfiguration.MyService.RSController;
AddSharedFolder(ctr.repositoryName, ctr.repositoryDomain,
                ctr.repositoryUsername, ctr.repositoryPassword);

, .

+2

, .

, , .

+1

it would be easier (rather than victim-type security) to do something like:

var controller = myConfigurationHandler.MyConfiguration.MyService.RSController;

AddSharedFolder( controller.repositoryName, controller.repositoryDomain, controller.repositoryUsername, controller.repositoryPassword);
+1
source

This is not the right way to do this. The correct way is to enter a variable for the type in which the properties are defined. Something like that:

var controller = myConfigurationHandler.MyConfiguration.MyService.RSController;

AddSharedFolder(
  controller.repositoryName,
  controller.repositoryDomain,
  controller.repositoryUsername,
  controller.repositoryPassword);
+1
source

All Articles