Valip
Valip

Reputation: 4620

How to return an array of integers using C# Interop?

I'm trying to return an array of integers and can't get it to work...

Below id my code that has the following error on return array

Cannot implicitly convert type 'int[]' to 'int'

  public int getIndexes(int num) 
    {
        var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
        var wsEvars = wb.Sheets["Evars"];


        Excel.Worksheet sheet = null;
        if (num == 0) sheet = wsEvars;

        if (num != 2)
        {
            var rng = (Excel.Range)sheet.Range[sheet.Cells[3, 2], sheet.Cells[3, 27]];
            var wsValues = rng.Cells.Value;
            int scopeIndex = 0;
            int methodIndex = 0;
            int delimiterIndex = 0;
            int formatIndex = 0;
            int count = 0;

            foreach (var head in wsValues)
            {
                if (head == "*Scope")
                    scopeIndex = count + 1;
                if (head == "Set Method")
                    methodIndex = count + 1;
                if (head == "Delimiter")
                    delimiterIndex = count + 1;
                if (head == "Format")
                    formatIndex = count + 1;
            }
            int[] array = new int[]{scopeIndex, methodIndex, delimiterIndex, formatIndex};
            return array;
        }
    }

Upvotes: 1

Views: 167

Answers (1)

NicoRiff
NicoRiff

Reputation: 4883

The problem is that your method is returning an int and not an int[] as you want. Also, yo are doing the return inside the if block, and that won´t ensure that the return will be hit because that will only happen if the condition is true. What about if the condition is false? You are not returning anything in that case. Get the return out of the block:

public int[] getIndexes(int num) 
{
    int[] array = null;
    var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
    var wsEvars = wb.Sheets["Evars"];


    Excel.Worksheet sheet = null;
    if (num == 0) sheet = wsEvars;

    if (num != 2)
    {
        var rng = (Excel.Range)sheet.Range[sheet.Cells[3, 2], sheet.Cells[3, 27]];
        var wsValues = rng.Cells.Value;
        int scopeIndex = 0;
        int methodIndex = 0;
        int delimiterIndex = 0;
        int formatIndex = 0;
        int count = 0;

        foreach (var head in wsValues)
        {
            if (head == "*Scope")
                scopeIndex = count + 1;
            if (head == "Set Method")
                methodIndex = count + 1;
            if (head == "Delimiter")
                delimiterIndex = count + 1;
            if (head == "Format")
                formatIndex = count + 1;
        }
        array = new int[]{scopeIndex, methodIndex, delimiterIndex, formatIndex};
    }
    return array;
}

Upvotes: 2

Related Questions