I'm not very familiar with C# and I've not been able to find a reasonable answer anywhere. I simply want to return an object from a function that to the caller is opaque. I still want the user to be able to pass the object around, I just don't really want them calling any of the methods on the object.
In C++, you'd simply return a void* and then a function receiving that object would cast it to its appropriate type and call the methods on it.
public class Blob
{
public void Method1() { do_something(); }
public void Method2() { do_something_else(); }
}
public class BlobMaker
{
public Blob CreateBlob() { return new Blob(); } // This needs to return something opaque
}
public class BlobUser
{
public void ConsumeBlob(var b) // Method would take the opaque type
{
Blob newBlob = (Blob)b;
b.Method1();
b.Method2();
}
}
public class MainApp
{
BlobMaker m = new BlobMaker();
var obj = m.CreateBlob(); // obj returned by BlobMaker should be opaque.
obj.Method1(); // This should not be allowed
obj.Method2(); // This should not be allowed
BlobUser user = new BlobUser();
user.ConsumeBlob(obj);
}
In my case, I simply don't want to completely trust the user to have access to the Blob methods, so I want the object to be opaque. In the Win32 API this is done all the time with all sorts of Windows structures being opaque as void* pointers.
Now I know that you can use "unsafe" and probably do exactly the same thing in C#, but I was wondering if there was a better way in C# to do this?
** EDIT ** Just ignore me people.... I'm being a loony... the answer is simple. All that method has to do is return object instead of Blob and it done. Sorry people, it was a certified brain fart.