java.lang.Void in C#? - c#

I am currently working with .Net 2.0 and have an interface whose generic type is used to define a method's return type. Something like
interface IExecutor<T> {
T Execute() { ... }
}
My problem is that some classes that implement this interface do not really need to return anything.
In Java you can use java.lang.Void for this purpose, but after quite a bit of searching I found no equivalent in C#. More generically, I also did not find a good way around this problem. I tried to find how people would do this with delegates, but found nothing either - which makes me believe that the problem is that I suck at searching :)
So what's the best way to solve this? How would you do it?
Thanks!

You're going to have to either just use Object and return null, create your own object to represent void, or just make a separate interface that returns void.
Here's an idea for the second one:
public class Void
{
public static readonly Void Instance = null; // You don't even need this line
private Void() {}
}
that way someone can't create an instance of the class. But you have something to represent it. I think this might be the most elegant way of doing what you want.
Also, you might want to make the class sealed as well.

Just use Object as the type , and return null.
That means you might need to write an adapter if you need to call a delecate who does in fact have a void return type

Related

void in C# generics?

I have a generic method that takes a request and provides a response.
public Tres DoSomething<Tres, Treq>(Tres response, Treq request)
{/*stuff*/}
But I don't always want a response for my request, and I don't always want to feed request data to get a response. I also don't want to have to copy and paste methods in their entirety to make minor changes. What I want, is to be able to do this:
public Tre DoSomething<Tres>(Tres response)
{
return DoSomething<Tres, void>(response, null);
}
Is this feasible in some manner? It seems that specifically using void doesn't work, but I'm hoping to find something analogous.
You cannot use void, but you can use object: it is a little inconvenience because your would-be-void functions need to return null, but if it unifies your code, it should be a small price to pay.
This inability to use void as a return type is at least partially responsible for a split between the Func<...> and Action<...> families of generic delegates: had it been possible to return void, all Action<X,Y,Z> would become simply Func<X,Y,Z,void>. Unfortunately, this is not possible.
No, unfortunately not. If void were a "real" type (like unit in F#, for example) life would be a lot simpler in many ways. In particular, we wouldn't need both the Func<T> and Action<T> families - there'd just be Func<void> instead of Action, Func<T, void> instead of Action<T> etc.
It would also make async simpler - there'd be no need for the non-generic Task type at all - we'd just have Task<void>.
Unfortunately, that's not the way the C# or .NET type systems work...
Here is what you can do. As #JohnSkeet said there is no unit type in C#, so make it yourself!
public sealed class ThankYou {
private ThankYou() { }
private readonly static ThankYou bye = new ThankYou();
public static ThankYou Bye { get { return bye; } }
}
Now you can always use Func<..., ThankYou> instead of Action<...>
public ThankYou MethodWithNoResult() {
/* do things */
return ThankYou.Bye;
}
Or use something already made by the Rx team: http://msdn.microsoft.com/en-us/library/system.reactive.unit%28v=VS.103%29.aspx
You could simply use Object as others have suggested. Or Int32 which I have seen some use. Using Int32 introduces a "dummy" number (use 0), but at least you can't put any big and exotic object into an Int32 reference (structs are sealed).
You could also write you own "void" type:
public sealed class MyVoid
{
MyVoid()
{
throw new InvalidOperationException("Don't instantiate MyVoid.");
}
}
MyVoid references are allowed (it's not a static class) but can only be null. The instance constructor is private (and if someone tries to call this private constructor through reflection, an exception will be thrown at them).
Since value tuples were introduced (2017, .NET 4.7), it is maybe natural to use the struct ValueTuple (the 0-tuple, the non-generic variant) instead of such a MyVoid. Its instance has a ToString() that returns "()", so it looks like a zero-tuple. As of the current version of C#, you cannot use the tokens () in code to get an instance. You can use default(ValueTuple) or just default (when the type can be inferred from the context) instead.
I like the idea by Aleksey Bykov above, but it could be simplified a bit
public sealed class Nothing {
public static Nothing AtAll { get { return null; } }
}
As I see no apparent reason why Nothing.AtAll could not just give null
The same idea (or the one by Jeppe Stig Nielsen) is also great for usage with typed classes.
E.g. if the type is only used to describe the arguments to a procedure/function passed as an argument to some method, and it itself does not take any arguments.
(You will still need to either make a dummy wrapper or to allow an optional "Nothing". But IMHO the class usage looks nice with myClass<Nothing> )
void myProcWithNoArguments(Nothing Dummy){
myProcWithNoArguments(){
}
or
void myProcWithNoArguments(Nothing Dummy=null){
...
}
void, though a type, is only valid as a return type of a method.
There is no way around this limitation of void.
What I currently do is create custom sealed types with private constructor. This is better than throwing exceptions in the c-tor because you don't have to get until runtime to figure out the situation is incorrect. It is subtly better than returning a static instance because you don't have to allocate even once. It is subtly better than returning static null because it is less verbose on the call side. The only thing the caller can do is give null.
public sealed class Void {
private Void() { }
}
public sealed class None {
private None() { }
}

A scenario where static virtual methods make sense

I know that virtual and static methods are opposing concepts, but I think that it could make sense sometimes to use them together. There have been quite a bunch of similiar question on SO on this topic, but the following scenario has not been covered yet.
There's a C# interface that looks like this:
interface IVertexMeshLoader
{
VertexMesh LoadFromFile(string fname);
}
An implementation of that could look like this:
class VertexMeshLoaderObj : IVertexMeshLoader
{
public VertexMesh LoadFromFile(string fname) { .. }
}
Now I would like to be able to call method without an object instance, but I cannot make the LoadFromFile() method static, because it implements the interface.
The best solution I worked out so far is to write a static method LoadFromFileStatic() that contains the actual code. The LoadFromFile() then just calls it. Not very pretty, imho.
I could also create an instance of VertexMeshLoadObj every time I want to call the method, but that is even worse.
Are there better ways? Thanks :-)
Here's another option. Provide an explicit implementation of the interface which just calls the static method. It allows them to have the same name
class VertexMeshLoaderObj : IVertexMeshLoader
{
VertexMesh IVertexMeshLoader.LoadFromFile(string fname) {
LoadFromFile(fname);
}
public static VertexMesh LoadFromFile(fname) {
...
}
}
If you must do this, create a singleton instance of IVertexMeshLoader and access that
Even if you're only interested in the vtable of the object and not in the actual members, you need an object instance to know what method to call.
So even if the actual implementation doesn't seem to depend on the instance, it in fact does.
You're not using "static virtual" methods but really virtual ones.

Instantiating an Internal class and casting it as a given type

Following up on InternalsVisibleTo. I have looked at c# Instantiating Internal class with private constructor, and this has helped but I'm trying to cast the returned object as the internal type and, honestly I'm not 100% that that is possible.
I'm trying the route of Reflection to fix this issue, but I'm having a tough time trying to figure out how to instantiate an internal type with private methods using reflection. I can go as far as pulling the type and getting the constructor and creating an object.
How would I preform the cast of the object if the type I wish to cast is an internal type.?
public object InitPrivateCoreObjects(string Type)
{
Assembly Core = Assembly.Load("Stuff.Core, Version=0.3.3881.21340, Culture=neutral, PublicKeyToken=4fe470e63e2d354e");
Type TypeToReflect = Core.GetType("Stuff.Core.AssemblyWithIdentifer");
object o = Activator.CreateInstance(TypeToReflect);
MethodInfo mi = TypeToReflect.GetMethod("AssemblyWithIdentifer");
object newObject = mi.Invoke(o,null);
//alternatively
//ConstructorInfo ctor = TypeToReflect.GetConstructor(new Type[]{TypeToReflect.GetType()});
//ctor.Invoke(newObject, null);
return newObject;
}
I can get the type of the internal class,
I can call the constructor and instantiate an object of the type. However, since I don’t have any access to the internal type I can’t cast it and manipulate it from there.
I understand I can use Reflection.Emit to create a new class based on that type, but if I'm going that route then I might as well just copy the entire contents of the project I'm trying to access into my test project. This would be really wastefully and pointless and would require me to throw in stuff from other projects and creating a mess and it's absolutely not the route I want to go at this time.
I've seen examples accessing individual methods and properties but none that instantiate an entire class. I'm not 100% sure it's possible since in the order of operations reflection happens before access modifiers are looked at.
Can this be done, and if so, how?
For clairification sake I wanted to use the instantiated object for testing purposes and [Assembly:InternalsVisibleTo("")] wasn't working due to bug which I'm currently working around. See here for original question.
Given that you only know the type at execution time, there's really no such concept as "returning the object as the internal type". Think about what you'd want the method signature to look like... there's no way you could express it.
If the calling code knows about it in a strongly typed way, you should make the code generic instead:
public T InitPrivateCoreObjects<T>()
{
Type type = typeof(T);
...
return (T) newObject;
}
... but if the calling code doesn't know about it, that's not helpful to it.
If you could explain more about why you think you want this ability, we could try to suggest alteratives.
I can use Reflection.Emit to create a new class based on that type
Not really: code generated using Reflection.Emit follows the same rules as your own C#. You can't use it to bypass internal protection.
I've seen examples accessing individual methods and properties
That's what you'll need to do: use reflection to look up and invoke individual methods and properties.
A couple of alternatives:
Modify the internal class to implement some interface, and make that interface public. Call methods on the interface as normal.
Get [InternalsVisibleTo] working. This is the right way to go.
This is not really a direct answer to your question, but you may find this useful:
ExposedObject
If you don't have access to the internal type, nor does that type implement any public interface that you consider sufficient to interact with it, but you know beforehand the names and signatures of members on that type, this is probably your best choice.

IsAssignableFrom, IsInstanceOf and BaseType testing

It's just a service locater type of pattern I am trying to implement, where I'd like to catch an attempt to register an implementation to an interface it doesn't belong to, as in:
public void Add(Type interfaceType, object implementingObject)
{
// ... check for nulls
// NO GOOD
if(!implementingObject.GetType().IsAssignableFrom(interfaceType)...
// NO GOOD
if(!implementingObject.GetType().IsInstanceOf(interfaceType)...
// FINALLY!
if(!implementingObject.GetType().BaseType.IsAssignableFrom(interfaceType)...
// ... ok, add it
}
Now I finaly figured out to use BaseType.IsInstanceOf by looking inside NUnit's isInstanceOf assertion, but it still seems unituitive.
Can someone explain why this makes sense? Is there some easier way to do this?
The way to look at it is from left to right, like you would normally when making an assignment in a language.
So in C#, the equivalent of calling assigningTo.IsAssignableFrom(assigningFrom) (or any of the other methods you mention) is to think of it as "will the following code work":
<assigningTo type> variable = <instance of assigningFrom>;
Applying that to your code, you want to use:
interfaceType.IsAssignableFrom(implementingObject.GetType())
interfaceType.IsAssignableFrom(implementingObject.GetType().BaseType)
The logic being you want to see if any of the types on the implementing object can be assigned to the interface type, or, in other words, if the implementing object can be assigned to interfaceType.
I think you want:
interfaceType.IsAssignableFrom(implementingObject.GetType())
Why would a concrete type be assignable from an interface?

Should a c# class generate instances of itself?

I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.
I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.
List<CallRates> cr = CallRates.ProcessCallsFile(file);
It is perfectly fine to get object(s) of its own from the static method.
e.g.
One of the dot net libraries does the same thing as you did,
XmlReadrer reader = XmlReader.Create(filepathString);
Sure that's fine, even encouraged in some instances. There are several design patterns that deal with object creation, and a few of them do just what you're describing.
I often use this pattern when I need to check the validity of parameters. It is strongly discouraged to throw an exception from a constructor. It's not so bad from a factory method, or you can choose to return null.
Seems fine to me. In other languages you would probably write a function, but in a language like C#, static methods take up that role.
It is ok. What you just created is something like a simple factory method. You have a static method that creates a valid instance of a type. Actually your method doesn't even have to be static and you still have a valid code. There is a design pattern (Prototype) that creates a new valid object from an existing object. See details at http://www.dofactory.com/Patterns/PatternPrototype.aspx.
Sure, for simple parsing (or similar) scenarios - I actually prefer the factory method be part of the class. Yes - it does break SRP, but it fulfills KISS - so I call it a net win. For larger apps, or more complicated parsing routines - it makes more sense to have it be an external factory class.
For your particular case, I'd probably prefer a method that took in an IEnumerable<string> instead of a filename - that'd still give you the parsing logic, but allow easy unit tests and "reuse". The caller can wrap the file into an IEnumerable easily enough.
Factory methods are often a good design. When I write them in C#, I call them 'New', so that:
new MyClass()
becomes
MyClass.New()
Trivially it's implemented like this:
class MyClass
{
public static MyClass New()
{
return new MyClass();
}
}
Mostly I do this when there are additional conditions about whether to actually create the class or just return null, or whether to return MyClass or something derived from it.
I sometimes use public static methods as an alternative to constructor overloading.
Especially in situations where it is not nice to rely on parameter types alone to indicate what kind of object construction is intended.
I'm a fan of having static methods return instances, as suggested plenty of times, above.
#Paul: don't forget to tick the comment above, which you find is the best answer.
Just like to point out
"generate new instances of itself by calling one of its own constructors"
It is not from the constructor, it is from the static method.
I generally use this when I need instant implementations of a class. For example
public class Car
{
public static Car RedExpensiveCar = new Car("Red", 250000);
public Car()
{
}
public Car(string color, int price)
{
Color = color;
Price = price;
}
public string Color { get; set; }
public int Price { get; set; }
}
And with this, I don't need to remember or write constructor parameters in my code.
Car car = Car.RedExpensiveCar;
It's perfectly acceptable to do this. When I do, I typically make the real constructors for the class private so that it's clear that the only way to construct instances is through the static method.
This is very useful in cases where "construction" may not always return a new instance. For example, you may want to return a previously cached object instead.

Categories

Resources