Depending on the length of your method, this may be the situation for polymorphism:
As noted in other answers, string and StringBuilder not related to each other. Therefore, your only chance to use the same method for them is to create wrappers for these two types that are interconnected.
You can define the base wrapper class using your method as follows:
public abstract class ScannableStringBase { public abstract int Length { get; } public abstract char this[int index] { get; } public int PositionOfTheSecondWord() { int pos = 0; int state = 0; char c; int length = this.Length; while (pos <= length - 1) { c = this[pos]; if (c == ' ' || c == '\n')
From this class, derive subclasses that handle the required value types:
public class ScannableString : ScannableStringBase { public ScannableString(string value) { this.stringValue = value; } private readonly string stringValue; public override int Length { get { return stringValue.Length; } } public override char this[int index] { get { return stringValue[index]; } } } public class ScannableStringBuilder : ScannableStringBase { public ScannableString(stringBuilder value) { this.stringBuilder = value; } private readonly string stringBuilder; public override int Length { get { return stringBuilder.Length; } } public override char this[int index] { get { return stringBuilder[index]; } } }
To summarize, you get:
- There is no code duplication because
PositionOfTheSecondWord() is defined only once, in the base class. - Type is security because your
PositionOfTheSecondWord() method cannot be called by anything other than string or StringBuilder . - Extensibility, because if you ever find that you want to support the third type, you can simply derive another class from
ScannableStringBase .
One possible flaw may be that you must distinguish the type for analysis somewhere in advance, so you can decide whether to create instances of ScannableString or ScannableStringBuilder .
source share