1

I'm quite new to C# and have been running some conversion from VB.NET to C#.

I understand indexing doesn't work with Arrays in C#, which is causing me a bit of trouble.

For example, the line:

myUserName = Conversions.ToString(myUserNameFields[0]);

Gives an error that one cannot apply indexing with [] to an expression of type array

I was hoping this would be a quick fix but I've been struggling to fix it. I've found similar problems from Googling:

Cannot apply indexing with [] to an expression of type 'System.Array' with C#

...but struggling to directly apply this to my code without completely overhauling it.

Is there a quick fix to something like this?

    internal static string getCurrentUserName()
    {
        string myUserName;
        myUserName = MyProject.User.Name;
        Array myUserNameFields = myUserName.Split('\\');
        if (myUserNameFields.Length == 1)
        {
            myUserName = Conversions.ToString(myUserNameFields[0]);
        }
        else
        {
            myUserName = Conversions.ToString(myUserNameFields[1]);
        }

        return myUserName;
    }
3
  • 5
    Don't declare it as Array, declare it as string[] or just use var. Commented Dec 28, 2020 at 15:55
  • Ah thanks! That was simpler than I thought it would be Commented Dec 28, 2020 at 15:59
  • 2
    String.Split returns a string[] array in VB.NET and C#. Don't cast it to an Array Commented Dec 28, 2020 at 15:59

1 Answer 1

2

Corrected C#:

internal static string GetCurrentUserName() //methods, even non public ones, use PascalCase
{
    var myUserName = MyProject.User.Name;          //do not declare then assign on the next line. Use var where the type on the right is obvious
    var myUserNameFields = myUserName.Split('\\'); //use var
    if (myUserNameFields.Length == 1)
    {
        myUserName = myUserNameFields[0];          //do not use Conversions.ToString to convert a string to a string. myUserNameFields is already a string; it needs no conversion
    }
    else
    {
        myUserName = myUserNameFields[1];          
    }

    return myUserName;
}

Consider also:

internal static string GetCurrentUserName() 
{
    var ns = MyProject.User.Name.Split('\\'); 
    return ns.Length == 1 ? ns[0] : ns[1];
}

Or even this, if you're after the joe in usernames that are like joe or domain\joe:

internal static string GetCurrentUserName() 
{
    return MyProject.User.Name.Split('\\').Last();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks for this! This helps a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.