Search code examples
c#variablesinitialization

Can we use uninitalizated char in the method?


how to understand if the first option is clear - we made an initalization of char[] tmp, but second option is unclear for me, can we use the 'new char[]' without initalization to the name of variables in the method?

string msg = "Suresh,Rohini,Trishika,-Praveen%Sateesh";
char[] tmp;
string[] strarray = msg.Split(tmp = new char[] { ',', '-', '%' },
    StringSplitOptions.RemoveEmptyEntries);

string msg = "Suresh,Rohini,Trishika,-Praveen%Sateesh";
string[] strarray = msg.Split(new char[] { ',', '-', '%' },
    StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strarray.Length; i++)

Solution

  • The first one is a but redundant. The method takes an array of char. It doesn't really matter how you pass it in.

    • In the first example you are creating and assign and passing it in, in the one go
    • In the second example you are creating it on-the-fly.

    You could do this ass well

    string msg = "Suresh,Rohini,Trishika,-Praveen%Sateesh";
    char[] tmp = new char[] { ',', '-', '%' }
    string[] strarray = msg.Split(tmp, StringSplitOptions.RemoveEmptyEntries);
    

    or

    string msg = "Suresh,Rohini,Trishika,-Praveen%Sateesh";
    string[] strarray = msg.Split(new char[] { ',', '-', '%' },
        StringSplitOptions.RemoveEmptyEntries);
    

    In the example you had, you could use temp it again. However. i think its a but messy and not as readable

    string msg = "Suresh,Rohini,Trishika,-Praveen%Sateesh";
    char[] tmp;
    string[] strarray = msg.Split(tmp = new char[] { ',', '-', '%' },
        StringSplitOptions.RemoveEmptyEntries);
    
    // we just reused temp!!!
    string[] strarray2 = msg.Split(tmp, StringSplitOptions.RemoveEmptyEntries);