'Convert connection string from VB to C#
I am trying to convert the following in VB (which works fine):
DBConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString
To C#:
DBConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString;
However I get the following error in C#:
Non-invocable member 'ConfigurationManager.ConnectionStrings' cannot be used like a method.
What then would be the proper way to convert to C# ?
Solution 1:[1]
Since ConnectionStrings is a collection with an indexer you have to use [...] in C#
DBConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[GlobalVariables.strConnection].ConnectionString;
Here's the indexer you're using.
Solution 2:[2]
In both VB and C# we use ( ) around arguments to methods, and the ( after a word representing a method will cause the method to be run
In VB things that behave like arrays (arrays, lists, dictionaries etc) are indexed with the same ( )
Dim arr = "a b c".Split()
Dim b = arr(1)
..but in c# we use [ ] for indexing
var arr = "a b c".Split();
var b = arr[1];
If you get "non invocable member cannot be used like a method" when converting VB to C#, check anywhere you've used ( ) that should be [ ]. An additional hint in VS2019+ is look at the color of the thing before the (; if it's a method it's yellow. Properties (that cannot be called) are white. Because ( is only ever used for method calling in c#, and not for indexing, it's a mistake to put it next to a white thing
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Schmelter |
| Solution 2 |
