Andrus said:
Pete,
Implement the concatenate using supported operations, rather than
made-up ones.
![Smile :) :)](/styles/default/custom/smilies/smile.gif)
For example:
override string[] RequiredFields
{
get
{
string[] rgstrBase = base.RequiredFields,
rgstrThis = { "field2" },
rgstrAll = new string[rgstrBase.Length +
rgstrThis.Length];
rgstrBase.CopyTo(rgstrAll, 0);
rgstrBase.CopyTo(rgstrAll, rgstrBase.Length);
return rgstrAll;
}
}
You may want to refactor the concatenation into a helper method (e.g.
extension method, static method in the base class, etc.) so that
subclasses only have to provide their specific field array, rather
than copying the concatenation code over and over.
I expected singe line command in every subclass.
Do you mean "single"? Why did you expect that?
This code looks too complicated and difficult to read.
Feel free to make it simpler and easier to read, if you can.
If this makes things simpler I can change string[] type to something
other, eq. IList<string> ?
then you can use said:
Or how to implement this in base class only ?
As I mentioned, you could move all the code that does the real work into
a single helper method, so that each sub-class only needs to call that
one method. This would be similar to using the Enumerable.Concat<T>()
extension method, except it would be your own method, specific to
whatever data type it is you want to support (e.g. string[]).
Depending on your exact needs, it may be that doing this using a virtual
class member isn't the best way anyway. If you can use the specific
type name, it might make more sense to do it as a static member, using
the static constructor. For example:
class Base
{
private static IEnumerable<string> _rgstrFields =
new string[] { "field1" };
public static IEnumerable<string> RequiredFields
{
get { return _rgstrFields; }
}
}
class Derived : Base
{
private static IEnumerable<string> _rgstrFields;
static Derived()
{
_rgstrFields = Base.RequiredFields.Concat(new string[] {
"field2" });
}
public static IEnumerable<string> RequiredFields
{
get { return _rgstrFields; }
}
}
Alternatively, if you really need the polymorphic behavior, use the same
static initialization, but make the RequiredFields property a virtual
instance member that just returns the value of the class's own static
member.
The above suggestion requires explicitly naming the base class in the
static constructor of derived classes, which I don't think is all that
bad. You can avoid that with more complicated initialization techniques
(e.g. type-based dictionary), but IMHO simpler is better.
Pete