String as char [] array in C # 3.0?

The C # 3.0 spec has the following code example in section 10.6.1.3 Output Parameters:

using System;
class Test
{
    static void SplitPath(string path, out string dir, out string name) {
        int i = path.Length;
        while (i > 0) {
            char ch = path[i – 1];
            if (ch == '\\' || ch == '/' || ch == ':') break;
            i--;
        }
        dir = path.Substring(0, i);
        name = path.Substring(i);
    }
    static void Main() {
        string dir, name;
        SplitPath("c:\\Windows\\System\\hello.txt", out dir, out name);
        Console.WriteLine(dir);
        Console.WriteLine(name);
    }
}

      

I cannot get this code to compile in VS2005 / C # 2.0. Has the behavior of strings been changed in C # 3.0 so that a string can be cast to a char [] array without explicitly converting it (the "ch = path [i-1]" statement)?

+1


source to share


6 answers


This is an invalid '-' character. Change to '-'



+6


source


What error are you getting?



System.String has [] accessors since .NET v1.0

+1


source


According to MSDN ( http://msdn.microsoft.com/en-us/library/362314fe(VS.71).aspx ) this was possible even in .net 1.1, you can of course have

string myString = "Filip Ekberg";

And then enter the first char by doing myString [0]

0


source


The dash you see in your code block is an em-dash character, not a minus. They are similar, but they are different. Wherever you cut and paste the code, it changed it to the wrong character.

char ch = path[i - 1];

      

is perfectly valid (as long as - - minus, not dash)

0


source


In the sidebar, why would you separate the path and filename? There are many useful functions for doing this in the Path class .

Use Path.GetFileName () for the file name, Path.GetDirectoryName () for the directory name.

0


source


This works for me, but the code you pasted in your question has an "m-dash" character (hex 96) instead of a minus sign (hex 2D) - maybe this is a font issue?

0


source







All Articles