0

I'm getting this error in new keyword.

//Code:

  public static string[] SplitStrings(string inboundString, char splitChar)
        {
            if(inboundString.Contains(splitChar))
            {
                return new[] { inboundString.Split(splitChar) };
            }
        }
4
  • Since String.Split() method returns an array, you are creating an array of arrays. Just remove new [] and you should be fine. And you need to return another array (an empty array maybe) for your else part to prevent not all code paths return a value error. Commented Aug 7, 2014 at 14:12
  • 1
    Why do you use if(inboundString.Contains(splitChar)) at all? That costs CPU time for no added value. or do you want to return something else if inboundString doesn't contain the char? Commented Aug 7, 2014 at 14:14
  • 1
    In fact, why not just call inboundString.Split(splitChar) in the calling code? Does this function add any additional value? Commented Aug 7, 2014 at 14:18
  • @TimSchmelter: if it doesnt contains dont it throw an error? Commented Aug 7, 2014 at 14:20

2 Answers 2

3

You don't need to create a new array the return from split works just fine.

public static string[] SplitStrings(string inboundString, char splitChar)
     {
        if(inboundString.Contains(splitChar))
        {
            return inboundString.Split(splitChar);
        }
        else 
        {
          return new string[] {};
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

Try it like this

        public static string[] SplitStrings(string inboundString, char splitChar)
        {               
             return inboundString.Split(splitChar);               
        }

String.Split itself returns a string[] so you don`t need to initialize a new one.

5 Comments

How can i handle the else part? any ideas??
@SanthoshKumar, it depends on what you want to return if the split character is not found in your string
@SanthoshKumar - Hogan`s idea of returning new string[] {}; will be good enough
Will that return my value if split char is not found?
@SanthoshKumar - see the modified method. It will return the spllited string if splitChar is not empty. And it will return string[] {inboundString} if it is.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.