I have the following class which is quite wide usely throughout my application :
public class ResultStatus
{
public Int32 Id {get; protected set}
public ErrorCode ErrorCode {get; protected set;}
List<string> UserMessages {get; protected set;}
protected ResultStatus (Int32 id, ErrorCode errorCode, List<string> userMessages)
{
Id = id;
ErrorCode = errorCode;
UserMessages = userMessages;
}
public static ResultStatus Success (int32 id, ErrorCode errorCode, IEnumerable<string> userMessages)
{
ResultStatus resultStatus = new ResultStatus (id, errorCode, userMessages.ToList());
return resultStatus;
}
}
I am concerned with the casting from the IEnumerable type of the parameter to List() and Im thinking of changing the property UserMessages type from List to IEnumerable to avoid the cast.
However in the projects that use this class, sometimes a Count is applied or the list is accessed directly by index. So what I gain by avoiding a cast, I loose by using the Count of the IEnumerable for instance which iterates throughout the collection. What is the nice way of doing this? Leave it like this, List type property – parameter casting from IEnumerable to List or change the type of the property and not be concerned on the few Counts ?
To internally store the information you need to use a
List<T>or a similar structure. You can’t just save theIEnumerable<T>you got passed in. The enumerable might not be valid once the function returns, or it might only allow iterating once,…As for the type of public properties I like using
ReadOnlyCollection<T>.