I am phrasing my example in generic terms because it gets the point across without having to go into my specific problem details.
Suppose you had a bunch of methods that take strings as parameters. Suppose that one string were a person's "first name" and another were a person's "last name". There could be other strings like "favorite food".
Now, in your code, you keep finding runtime bugs because you are getting the parameters mixed up. You may switch the order of "first name" and "last name" or use one when you should have used the other. The value of strongly-typed languages is that it will find these bugs at build time rather than runtime.
So, one possible solution would be to just derive classes from string.
public class FirstName : String
{
}
public class LastName : String
{
}
Now, if you passed the wrong type of string the compiler would complain. The above is not possible because String is sealed. Also, the "using" statement will not work (I think) because the compiler will not complain when I mix them up.
using LastName = String;
Sure, I could build classes that wrap the string and then write cast conversion methods, but that seems like more trouble than it is worth.
I don't know what your aim is, but you seem to be serious about it :) So a possible solution would be to use a generic container class. It would indeed be less comfortable than inherit from the sealed classes.
public class Container<T>
{
public T Value { get; protected set; }
public Container(T value)
{
Value = value;
}
}
public class FirstName : Container<string>
{
public FirstName(string firstName) : base(firstName) { }
}
public class LastName : Container<string>
{
public LastName(string lastName) : base(lastName) { }
}
public class Age : Container<int>
{
public Age(int age) : base(age) { }
}
public class Program
{
public void Process(FirstName firstName, LastName lastName, Age age)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With