This should be a pretty trivial one.
Can C# return a type that is "force-cast", that is where the following fails:
private ICollection<string> _strings = new List<string>();
public IEnumerable<string> Strings
{
get
{
return ((IEnumerable<string>)_strings);
}
}
/* I should not know that Strings can be cast to ICollection */
public void AddToStrings()
{
ICollection<string> st = ((ICollection<string>)Strings); /* I should fail */
st.Add("MyString");
}
I'm aware I could do this:
public IEnumerable<string> Strings
{
get
{
return ((IEnumerable<string>)_strings.ToArray());
}
}
But this seems (1) unnecessary, (2) still doesn't stop them casting to an ICollection, just from adding and (3) I'm just plain curious about the general question.
Some people seem unsure about what I am trying to achieve here. I am trying to prevent outside classes from violating the contract I provide them. I have not said that Strings is an ICollection - it just so happens that I am using that internally - and as such no outside class should be able to treat my returned variable as an ICollection. I don't want to expose modification behaviour to them, and I don't want them to treat my variable as an ICollection in case I later change the way I generate that IEnumerable.
More generally, can I return an object as an instance of one of its more specific types, and prevent later casting to one of its more general types. For example, while you can yield a new IEnumerable, could you return an IDisposable object that cannot be cast back to whatever type it was (i.e. only has Dispose() and object methods callable)?
Ah ok, I see what you mean now...
public IEnumerable<string> Strings
{
get
{
foreach (var s in _strings) yield return s;
}
}
But it has nothing to do with boxing...
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