C
codymanix
Often you don't wish that clientcode does not depend on a certain
implementation of your methods:
class MyClass
{
public IList DoIt(){return new ArrayList();}
}
clientcode could now cast the return value in Arraylist. In a later version
you may find it more effective that your method returns an Array. This
change would break client code.
another example:
you want a list returned as readonly and, since wrappers are slow you simply
cast it to a interface that doesn't provide any modification methods.
IReadonlyList
{
public object this { get; }
}
INormalList : IReadonlyList
{
public object this { get; set;}
}
but now the problem is that the client could simply cast it back to a normal
list and modify it.
Now my proposal.
A modifier that, applied to a variable declaration or interface definition
forbids upcasting.
The result is an so called "strong interface" that cannot be upcasted no
matter what type the object is.
so that:
IReadonlyList r;
INormalList n = (INormalList)r;
will be caught by the compiler.
whereas
IReadonlyList r;
object o = r;
INormalList n = (INormalList)o;
cannot be detected at runtime, it has to throw an exception.
What do you think about this idea?
implementation of your methods:
class MyClass
{
public IList DoIt(){return new ArrayList();}
}
clientcode could now cast the return value in Arraylist. In a later version
you may find it more effective that your method returns an Array. This
change would break client code.
another example:
you want a list returned as readonly and, since wrappers are slow you simply
cast it to a interface that doesn't provide any modification methods.
IReadonlyList
{
public object this { get; }
}
INormalList : IReadonlyList
{
public object this { get; set;}
}
but now the problem is that the client could simply cast it back to a normal
list and modify it.
Now my proposal.
A modifier that, applied to a variable declaration or interface definition
forbids upcasting.
The result is an so called "strong interface" that cannot be upcasted no
matter what type the object is.
so that:
IReadonlyList r;
INormalList n = (INormalList)r;
will be caught by the compiler.
whereas
IReadonlyList r;
object o = r;
INormalList n = (INormalList)o;
cannot be detected at runtime, it has to throw an exception.
What do you think about this idea?