0

I have StoreProcedureConstant.cs file where I've defined constants. I am able to call the constants but can't do it with dynamic strings.

StoreProcedureConstant.cs

public const string testSP = "sp_testingtest";
public const string restSP = "sp_test1";
public const string SP1 = "sp_secondtest";

Service.cs

string[] paramlist = {"testSP","restSP","SP1"};
string[] except = {};
var newparams = paramlist.ToDictionary(key => key, value => value);
foreach (var param in newparams.Values)
{ 
   Data = CommonDBService.ExecuteNonQuery(StoreProcedureConstant.param);
   if (Data == false) 
   {
      except.Append(param);
   }
}

I have this other file Service.cs from where I am calling the constants from StoreProcedureConstant.cs file. I am not able to call constants like StoreProcedureConstant.param. So I've converted string array to dictionary but it is still not working.

I am new to c# and I think this is not possible. Please help!!

  • Are these lines the *only* things within your `StoredProcedureConstant.cs` file, or do you have more lines (a class and namespace, perhaps?) – Luke Feb 01 '23 at 15:43
  • I've namespace and public class defined. I am able to call the constants by their name but I want to call them based on the paramlist array. The array contains constant names. – beginnerdev Feb 01 '23 at 15:52
  • 1
    Does this answer your question? [How to get a property value based on the name](https://stackoverflow.com/questions/5508050/how-to-get-a-property-value-based-on-the-name) – Drag and Drop Feb 01 '23 at 16:02
  • 1
    Or _maybe_ you want to do something like: https://dotnetfiddle.net/jsU6NM – Fildor Feb 01 '23 at 16:52

1 Answers1

0

You need to do something like this:

string[] paramlist = {testSP,restSP,SP1};

But it seems like those names are not available (not in scope). You can possibly address this by adding a using for the StoreProcedureConstant namespace at the top of the Service.cs file, but you may also need to clarify the class name as part of the array.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Thank you, I can access those constant variables okay in the service.cs file. I want to call them by the paramlist strings. – beginnerdev Feb 01 '23 at 16:00
  • 2
    No, you don't. That's poor practice in a strongly-typed environment like this, because it can blow up at run time if there's ever a typo in Service.cs. One way (among many) this happens is later on in the program's life cycle someone renames, replaces, or retires a constant in StoredProcedureConstant.cs. If you use the actual variables, the compiler will catch this for you everywhere they're used. If you use strings, you have to find all the references manually, and it's easy to miss. – Joel Coehoorn Feb 01 '23 at 16:04
  • I agree, I didn't think about it this way. Thank you so much for the insight! – beginnerdev Feb 01 '23 at 16:45