2

I'm retrieving a row from a database that has an attribute which is a comma separated list of ID's

1,2,3,4,5

In my POCO is it possible to do something like this to get an array back?

public string SomeIDs 
{
    get 
    {
        return SomeIDs.split(',');
    }
    set;
}

Edit: Sorry, to clarify, I am setting with a string and want to return a string array

1
  • 3
    Well not quite like that, no. Your property getter is calling itself... one time expecting it to be a string, and one time trying to return a string array. Oh, and split should be Split... Commented Jun 1, 2015 at 14:41

3 Answers 3

7

You can't have a setter which accepts a string and returns a string[]. You'll need to expose one property which accepts a string, and a read-only property (as below) which returns a parsed array from that string:

private static readonly string[] emptyIds = new string[0];
public string SomeIds { get; set; }
public string[] ParsedIds 
{
    get 
    {
        return !string.IsNullOrEmpty(SomeIds) ? SomeIds.Split(',') : 
                                                emptyIds;
    }
}

Edit:

Sign up to request clarification or add additional context in comments.

9 Comments

But how can I set it with a string?
I would add a guard clause in the get to ensure that SomeIds is not null and has a value before splitting it. Just by adding if (!string.IsNullOrEmpty()) and returning an empty array if it fails the check.
@RobKing You got it :)
Enumerable.Empty<string>().ToArray() is a bit overkill IMHO: no need to create an iterator here. You could use new String[] {} or even better have a static readonly String[] EmptyIds = new String[] {} and return a reference to it.
You guys are really nit-picky :). Edited.
|
1

Is this what you need:

private string _ids;
public string[] SomeIDs
{
    get { return _ids.Split(','); }
}

Comments

-2

you can try this:

private string _someIDs;
public object SomeIDs
{
  get { return _someIDs.Split(','); }
  set { _someIDs = value as string; }
} 

Comments

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.