Casting of interfaces - c#

interfaces provide a useful abstraction capability. One can have a class Foo implement some interfaces, say A, B, and C. Some client code may get a reference of type A, others one of type B, etc. each actually the same Foo object but the interface exposing only a narrow subset of the functionality. Of course, evil client code can try to cast the A reference to Foo, then access the other functionality.How to prevent this?

This is called a "malicious cast" and you can prevent it by having a wrapper that implements only the narrow interface you want to expose (by delegating to a private reference to the object that you would have otherwise directly passed to the evil client).
However, if the client is not only evil, but powerful as well, he might be able to use reflection to get to the hidden reference anyway.

Normal inheritance will always allow it, you can do nothing with it. If you want to expose some class as interface but hide other methods use Adapter pattern (google it)

You can't. One workaround is to implement three proxy classes, one to implement each interface, that forward all calls to a single Foo instance.

The person who performs a malicious cast does so at their own risk. In almost all cases, you can safely assume that the user will not use an object in a manner outside the specified interface contract.
The only time you really need to use a proxy object is if you are exposing security-sensitive object to untrusted code. Otherwise, spend your time making clear documentation about how objects can be used and work under the assumption that it will be followed.

Hide the underlying object.
Let's say you have:
public interface A {
}
public class B implements A {
}
So, interface A implements just a subset of B's functionality. Effectively it hides parts of B. Your question is how to stop the user from downcasting A to a B.
B objectOfTypeB = (B)objectOfTypeA; // you don't want this
So, don't give the user access to class B. If the user can't import it, he can't instantiate it or downcast to it. So, he's force to use the interface and nothing more.
Change the above code to:
/* Publicly accessable interface */
public interface A {
}
/* Class hidden inside the package. */
public class B implements A {
}
Then, you can just have a function return an A, secure in the knowledge that the user can't use B.
/* Function that returns an A. */
public A foo() {
/* ... */
return objectOfTypeB;
}

You can use a Facade class.
This class should wrap a delegate of class Foo and then only expose interface methods of, say A and just forward them to the delegate.
On the other hand, you can prevent casting to Foo by declaring it package private and have a public factory method that returns just the interface A ( which in reality is Foo ). That way casting from other packages will not be possible ( still, somebody may play tricks with reflection ).

There is no really practical, non-invasive way to protect against this.
However, if your situation really requires this protection, use this utility class to create dynamic proxy (delegate) classes (adapted from Dynamic Proxy Classes - <50 lines of production code!!).
This will cause ClassCastExceptions at runtime if someone uses tries a malicious cast. You could even conditionalize the code to turn it off at production time (have newInstance() just return obj - the object to as the "proxy").
DynamicProxy.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DynamicProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj, Class<?>... interfaces) {
if (interfaces == null || interfaces.length == 0) {
throw new IllegalArgumentException("No interfaces");
}
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
interfaces,
new DynamicProxy(obj));
}
private DynamicProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
}
return result;
}
// ** DEMO CODE BELOW HERE **
interface A {
void methodA();
}
interface B {
void methodB();
}
static class Foo implements A, B {
public void methodA() { System.out.println("A"); }
public void methodB() { System.out.println("B"); }
}
public static void main(String[] args) {
Foo foo = new Foo(); // implements both interfaces
// calls foo's methods, but only A methods
A a = (A) DynamicProxy.newInstance(foo, A.class);
// calls foo's methods, but only B methods
B b = (B) DynamicProxy.newInstance(foo, B.class);
// calls foo's methods, but only B methods
A ab = (A) DynamicProxy.newInstance(foo, A.class, B.class);
a.methodA();
b.methodB();
ab.methodA();
((B) ab).methodB();
// ClassCastException: $Proxy0 cannot be cast to DynamicProxy$Foo
((Foo) a).methodA();
// ClassCastException: $Proxy1 cannot be cast to DynamicProxy$Foo
((Foo) b).methodB();
// ClassCastException: $Proxy0 cannot be cast to DynamicProxy$B
((B) a).methodB();
// ClassCastException: $DynamicProxy1 cannot be cast to DynamicProxy$A
((A) b).methodA();
}
}

Related

Implement a generic type to pass around

I am sure this is duplicate but I am not sure I am searching for the correct answers. Or understanding that it answers my question.
For 1 I think I am using my interface wrong. For 1 I break the rules of SOLID and am trying to clean it up. For example IReelWindow. I have things in there specific to ReelWindowTumble that the other ReelWindows don't use and throw not implemented errors. I started breaking it up into multiple interfaces but found i no longer had access to functions for ReelWindowTumble, even though I created a new interface for ITumble and still inherited from IReelWindow. The problem is in the functional code.
public interface IReelWindow
{
//stuff declared
void PopulateWindowTumble();
void PopulateWindow(int[] currentStops);
}
public class ReelWindow : IReelWindow
{
// implements most of it throwing exceptions when I don't use it.
public void PopulateWindow(int[] currentStops)
{
}
public void PopulateWindowTumble()
{
throw new NotImplementedException();
}
}
public class ReelWindowTumble : IReelWindow
{
// implements most of it throwing exceptions when I don't use it.
public void PopulateWindow(int[] currentStops)
{
}
void PopulateWindowTumble()
{
}
}
public class ReelWindowIndependent : IReelWindow
{
// implements most of it throwing exceptions when I don't use it.
public void PopulateWindow(int[] currentStops)
{
}
public void PopulateWindowTumble()
{
throw new NotImplementedException();
}
}
Here I declare a new IReelWindow and create a new ReelWindow based on client input. This works ok, as I just pass IReelWindow everywhere I want to use a ReelWindow.
I don't think this is the proper usage of my interface. If I use ICloneable, i don't declare a new object of ICloneable and pass it around.
But my intention is to create a Generic ReelWindow Type. I don't care what type of window the client creates. I just want to enforce what functions it should have as I use them specifically.
How do I declare a Generic ReelWindow that I can pass around without creating multiple functions that are identical but have strong types passed in?
public static IReelWindow CreateReelWindow(WindowType userSelectedWindowType, Paytable paytable)
{
IReelWindow _reelWindow;
if (userSelectedWindowType == WindowType.Standard)
{
_reelWindow = new ReelWindow(paytable.ColLengths, paytable.ReelContainer.Reels, paytable.WindowWidth, paytable.Lineset, paytable.ReelContainer.TotalPhysicalReelStop);
}
else if (userSelectedWindowType == WindowType.Tumble)
{
_reelWindow = new ReelWindowTumble(paytable.ColLengths, paytable.ReelContainer.Reels, paytable.WindowWidth, paytable.Lineset, paytable.ReelContainer.TotalPhysicalReelStop);
}
else if (userSelectedWindowType == WindowType.Independent)
{
_reelWindow = new ReelWindowIndependent(paytable.ColLengths, paytable.ReelContainer.Reels, paytable.WindowWidth, paytable.Lineset, paytable.ReelContainer.TotalPhysicalReelStop, paytable.ReelLengths, paytable.ReelStarts);
}
else
throw new ApplicationException("Unknown window type selected by user. Cannot continue.");
return _reelWindow;
}
Later in my code I use the reelwindows, and only pass in 'IReelWindow' as I don't care what type of reelwindow, the function will use it accordingly.
public abstract class AEval
{
public abstract double Evaluate(IReelWindow reelWindow, ref string flags, int currentStopsWeight);
public abstract double EvaluateVerbose(IReelWindow reelWindow, ref string flags, int currentStopsWeight);
}
The object that you are passing around is _reelWindow and while it implements IReelWindow, it is not an IReelWindow object. Instead it is one of your derived types: ReelWindow, ReelWindowTumble, ReelWindowIndependent, etc. Each of those derived types should be treated the same by your client (as you noted).
Let's pretend ReelWindow implements 2 methods from the interface, ReelWindowTumble implements 3 methods from the interface, and ReelWindowIndependent implements 10 methods from the interface. And the interface has a maximum of 10 methods to implement.
Using the language of your example, that means that ReelWindow will have 8 methods with NotImplementedException (NIE), ReelWindowTumble will have 7 methods NIE, and ReelWindowIndependent has 0 methods NIE.
What about your client code? Well, for all of this to make sense your client code should be calling all 10 of the interface methods while working with _reelWindow. That also means, using my example, that ReelWindowIndependent should work just fine with the client code because it has no NIE methods.
I'd say that your real problem is the NIE's. Remove those exceptions and instead return null. Then, in your client code, during flow of control, you can add statements to the effect of "if returned object is null, skip this section".
Remember, all objects inherit from 'object'. Those strongly typed return objects in your interface can be returned as 'object' too. That means any strongly typed object can be set to null. To repeat: try returning null value for methods with strongly typed return values and handling the null in your client code. Now, if the interface method has no return - it is marked void - then you don't need to worry about checking for null in your client code, nor would you need NIE: the method can be left blank and when called literally does nothing. If you ponder this, you might strive for interface design that does not use strongly typed return values. And that goes to Jamiec's comment: we need to know more about the interface.

Change method call for specific object

Looking at this question got me wondering if something similar is possible using the dark reflection ways of C#.
Say I have this code:
public class Foo
{
public void FooPrint() // can't change this implementation
{
Console.Write("Foo");
}
}
public class Bar
{
public Foo foo = new Foo();
public Bar()
{
//do some reflection magic with member foo here ?
}
public void FooPrintRewritten()
{
Console.Write("Haha, only for Bar.foo.");
}
}
class Program
{
static void Main(string[] args)
{
Foo a = new Foo();
a.FooPrint(); // should still print "Foo"
Bar bar = new Bar();
bar.foo.FooPrint(); // should print "Haha, only for Bar.foo."
}
}
Is what I ask for in the inlined comments in any way possible? Is there a way to re-bind a method call to another method for only a specific variable?
Yes I know this is ridiculous, no this shouldn't ever be used in production code. This is for the sake of curiosity.
Other answers have suggested ways in which you can achieve what you want on a functional level, which is arguably the sane thing to do, but I'll tackle the question directly: can this be done changing no code in the question except the implementation of Bar.Bar(), keeping Bar.foo of type Foo and changing nothing about Foo?
The answer is no. You cannot change the method table for a single object, which is basically what you're asking for here. The method table is part of the type, not the instance. If an expression f is of type Foo, and FooPrint is a non-virtual method of Foo, then the call f.FooPrint() will always resolve to Foo.FooPrint. Even worse, the compiler might choose to inline the call since that's obviously a safe optimization*. Where are your dark reflection ways now?
The only way to achieve this is to convince the compiler that calls to Foo.FooPrint should be treated specially, taking the instance into consideration. There are a few ways of doing so:
Foo.FooPrint could be made a delegate. The targets of a delegate call are specific per instance of the delegate.
Foo.FooPrint could be made a virtual, abstract or interface method. All of these are resolved based on the runtime type of the instance. Simply derive a class from Foo and away you go.
Foo could inherit from MarshalByRefObject. An MBRO, as it's commonly called, is treated specially by the jitter since (as the name implies) calls may need to be marshalled back. In particular, if Foo was an MBRO, you could create a RealProxy for it that will cough up a transparent proxy that resembles a real, actual Foo in almost all ways, right down to GetType(), except that you get to choose how calls are actually handled.
All of these approaches are used by various mocking/interceptor/proxy libraries, all of them require some change to Foo. The only approaches that require no (textual) change to Foo are those that rewrite the IL involved, like PostSharp or Microsoft Fakes, but I'd consider that cheating for purposes of this question.
* Technically, the C# standard says nothing about either method tables or permissible ways of inlining since those are implementation details, but it does say that Foo.FooPrint is always resolved in only one way without considering the instance (except that it must not be null).
Actually, there is a case for this type of behaviour under SRP of SOLID if you needed to separate implementations to maintain the principle (depending on how strictly you are adhering to SOLID ofc).
It's called the Interceptor pattern and used by Mocking libraries such as Moq.
Have a look at the following article on the subject for a good example of how the pattern can be used: C#: Why Decorate When You Can Intercept
Here's another way of overriding (virtual) methods when you instantiate a class
class Program
{
static void Main(string[] args)
{
Foo a = new Foo();
a.FooPrint(); // should still print "Foo"
Bar bar = new Bar();
bar.foo.FooPrint(); // should print "Haha, only for Bar.foo."
Console.Read();
}
}
public class Foo
{
public Action FooPrint = () => Console.WriteLine("Foo");
}
public class Bar
{
public Foo foo = new Foo()
{
FooPrint = () => Console.WriteLine("Haha, only for Bar.foo.")
};
}
this post explains how to make an override right when you instantiate a class.
However, it uses Func which requires a method which contains a return type that isnt void, thats why you'll want to use Action instead, as explained here
What about this, with still the same usage:
public class Wrapper : Foo
{
public new void FooPrint()
{
Console.Write("Haha, only for Bar.foo.");
}
}
public class Bar
{
public Wrapper foo = new Wrapper();
}

Factory of plain classes derived from generic specializations

I have a C# generic class B<T>. Also I have a set of derived classes Di : B<Ti>. All that classes are always created with the same set of parameters.
So it leads to spagetti code:
if (typeof(T) == typeof(A1)) {work with D1}
else if (typeof(T) == typeof(A2)) {work with D2}
...
Obviously I want to refactor the code in way it'll look like:
var dInst = GiveMeD<T>();
work with Di
How can I implement function GiveMeD<T>()?
UPDATE:
work with Di -> casting to base class B<T> and work with its interface.
The main problem here - each block of code differs in derived class constructor invocation.
If you want to refactor effectively the code this way then you must take into account that "working with D1" and "working with D2" must be the same and only the behavior must differ; that is, D1 and D2 must have a common "interface" (B<T>) and you should only leverage said "interface", otherwise you will start having spaghetti code all over the place again and ugly casts.
If this fits your needs (if it doesn't then you should reconsider your whole approach to the problem), the common pattern is to simply create a factory method where your spaghetti code will only be written once:
public static B<T> CreateD<T>()
{
if (T is A1) return ... //here you can create a new instance of D1 or return a cached one, etc.
else if (T is A2) return ...
}
A beautiful pattern I like to use when the consumer does not need know anything about D1, D2, etc. and only needs to know about B<T> is the following:
public class B<T>
{
public B<T> CreateD<T>()
{
if (T is A1) return ... //here you can create a new instance of D1 or return a cached one, etc.
else if (T is A2) return ...
...
}
private B() { } //note constructor is private, consumer can't create a B<T>
private class D1: B<A1> { ... } //private nested types, not visible outside B<T>.
private class D2: B<A2> { ... }
}
Now you have absolute control on how many Dis can be implemented, you expose one single general purpose B<T> and you guarantee to give back always the correctly specialized type without actually making the consumer have to know anything about it.

In C#, what are some rules of thumb for _where_ to clone objects?

Here's the situation: I am trying to determine the where part of cloning an object to avoid modifying the original.
I have two options:
Clone the object in the caller and pass the cloned object to a method ("callee"), thus preventing potential modification by the callee.
Clone the object in the callee because the callee modifies the object it is passed, this making the assumption that the caller never wants the argument object to be modified.
I found this 6-year-old answer with a variety of opinions. Unfortunately it doesn't seem there was a real consensus.
Passing copy of object to method -- who does the copying?
Here's my question in code-form:
Do I clone the object in the caller and pass the cloned object to the method?
public static void Main()
{
var foo = new Foo();
Bar.Baz(foo.DeepClone());
}
public static class Bar
{
public static void Baz(Foo foo)
{
/* ... modifies members in foo ... */
}
}
public class Foo { /* ... */ }
Do I clone the object in the callee?
public static void Main()
{
var foo = new Foo();
Bar.Baz(foo);
}
public static class Bar
{
public static void Baz(Foo foo)
{
foo = foo.DeepClone();
/* ... modifies members in foo ... */
}
}
public class Foo { /* ... */ }
So, my questions are:
What are some good rules of thumb for where to clone objects across languages, but especially in C# and .NET-land?
Regardless of the answer(s), what are some good ways to document the behavior of methods that modify arguments, or methods that clone objects?
Is the purpose of the method to mutate the object? Then don't clone inside of the method. You want the side-effects to happen. Usually, the method name would clearly call out the fact that a mutation is expected (e.g. UpdateCustomer).
If it is not the explicit purpose of the method to mutate its inputs then the mutation is an implementation detail and the method must see to it that the mutation does not leak out. It can do that by cloning.
Methods should not use their inputs as mere scratch space. Some in the Win32 APIs do that which is horribly confusing.
The best way to enforce (and document) constness is to define a read only interface and define your parameter as that interface. Anything that accepts the interface is constant and anything that accepts the full object might mutate the object.
If you are following this approach, the caller should be cloning if it does not want the side effects since we have given permission to the callee to modify the object by passing it a modifiable object.

C# virtual static method

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?
I know the concept has already been underlined but I did not find a simple answer to the previous question.
virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.
How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one
“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
The contradiction between "static" and "virtual" is only a C# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.
Too bad the choice of words made C# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.
Some Delphi beauty:
type
TFormClass = class of TForm;
var
formClass: TFormClass;
myForm: TForm;
begin
...
formClass = GetAnyFormClassYouWouldLike;
myForm = formClass.Create(nil);
myForm.Show;
end
Guys who say that there is no sense in static virtual methods - if you don't understand how this could be possible, it does not mean that it is impossible. There are languages that allow this!! Look at Delphi, for example.
I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.
Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.
To me that sounds like what you really want is a singleton object with delegated methods.
Let's put together an example:
public interface ICurrencyWriter {
string Write(int i);
string Write(float f);
}
public class DelegatedCurrencyWriter : ICurrencyWriter {
public DelegatedCurrencyWriter()
{
IntWriter = i => i.ToString();
FloatWriter = f => f.ToString();
}
public string Write(int i) { return IntWriter(i); }
public string Write(float f) { return FloatWriter(f); }
public Func<int, string> IntWriter { get; set; }
public Func<float, string> FloatWriter { get; set; }
}
public class SingletonCurrencyWriter {
public static DelegatedCurrencyWriter Writer {
get {
if (_writer == null)
_writer = new DelegatedCurrencyWriter();
return _writer;
}
}
}
in use:
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0
SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies
Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).
That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.
Yes it is possible.
The most wanted use case for that is to have factories which can be "overriden"
In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.
Example 1
Let's take a factory example:
class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}
You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:
class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B> { /* no create function */ }
B theb = B.Create(2); // Perfectly fine.
A thea = A.Create(0); // Here as well
Example 2 (advanced):
Let's define a static function to multiply matrices of values.
public abstract class Value<T> where T : Value<T> {
//This method is static but by subclassing T we can use virtual methods.
public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
return // Code to multiply two matrices using add and multiply;
}
public abstract T multiply(T other);
public abstract T add(T other);
public abstract T opposed();
public T minus(T other) {
return this.add(other.opposed());
}
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
protected double real;
/// Note: The use of MultiplyMatrix returns a Matrix of Number here.
public Matrix<T> timesVector(List<T> vector) {
return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
}
}
public class ComplexNumber : Number<ComplexNumber> {
protected double imag;
/// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}
Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber
Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
While technically it's not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think you're trying using C# extension methods.
From Microsoft Docs:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Check out Extension Methods (C# Programming Guide) for more details.
In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.
To summarize all the options presented:
This is not a part of C# because in it, static means "not bound to anything at runtime" as it has ever since C (and maybe earlier). static entities are bound to the declaring type (thus are able to access its other static entities), but only at compile time.
This is possible in other languages where a static equivalent (if needed at all) means "bound to a type object at runtime" instead. Examples include Delphi, Python, PHP.
This can be emulated in a number of ways which can be classified as:
Use runtime binding
Static methods with a singleton object or lookalike
Virtual method that returns the same for all instances
Redefined in a derived type to return a different result (constant or derived from static members of the redefining type)
Retrieves the type object from the instance
Use compile-time binding
Use a template that modifies the code for each derived type to access the same-named entities of that type, e.g. with the CRTP
The 2022+ answer, if you are running .Net 7 or above, is that now static virtual members is now supported in interfaces. Technically it's static abstract instead of "static virtual" but the effect is that same. Standard static methods signatures can be defined in an interface and implemented statically.
Here are a few examples on the usage and syntax in .Net 7

Categories