0

I keep getting error "cannot implicitly convert type 'string' to 'int'" in C#.

Following is my code that is getting error

    public static void CreateOpcItems()
    {
        RsiOPCAuto.OPCItems lclItems;
        lclItems = opcGroup.OPCItems;

        globalOpcItem[1] = lclItems.AddItem("[Orex_Brain_Mill2]gStnMill2.DATA.MillTemperature", 1);



    }
    public static object GetPlcValue(string pItem)
    {

        object lclObject = new object();
        globalOpcItem[pItem].Read(1, lclObject);

    }
  • 1
    What is not clear in the error message? – arrowd Jan 27 '18 at 07:27
  • 1
    The error is pretty clear - you're trying to use a `string` as an index to a collection (`globalOpcItem`), when it needs to be an `int`. – Tim Jan 27 '18 at 07:27

1 Answers1

0

you may either change your function to accept int:

public static object GetPlcValue(int pItem)
{

    object lclObject = new object();
    globalOpcItem[pItem].Read(1, lclObject);

}

or parse it:

public static object GetPlcValue(string pItem)
{

    object lclObject = new object();
    globalOpcItem[int.Parse(pItem)].Read(1, lclObject);

}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • 1
    The second approach is brittle - if the string isn't an int, the `int.Parse` method will throw a format exception (or something similar). Better option is #1; for the second I'd add more code and use `Int.TryParse` for more resilience. – Tim Jan 27 '18 at 07:31
  • @Tim, well I know it, but I want to suggest the possible solutions, if `pItem` is a number in string format he will need to parse it anyway, either before sending it to function or in it. and even if it's not parseable using `TryParse` may avoid errors but will give an incorrect answer – Ashkan Mobayen Khiabani Jan 27 '18 at 07:33
  • An incorrect answer to the OP's question, or an incorrect answer in the data retrieval? `TryParse` would allow the code to error out gracefully and not try and retrieve data in the case of a non-integer string, rather than throwing an exception that may or may not be caught at a higher level. – Tim Jan 27 '18 at 07:37
  • I have already tried these all methods then another error is coming like – Lasitha Fernando Jan 27 '18 at 07:45
  • The error is "No overload for method 'Read' takes 2 arguments" – Lasitha Fernando Jan 27 '18 at 07:47
  • 1
    @LasithaFernando this is not related to this question. you should check how many and which types of arguments `Read()` takes. – Ashkan Mobayen Khiabani Jan 27 '18 at 07:49