What is System.Void? - c#

I know that methods declared with void does not return anything.
But it seems that in C#, void is more than just a keyword, but a real type.
void is an alias for System.Void, like int that is for System.Int32.
Why am I not allowed to use that type? It does not make any sense, but these are just some thoughts about the logic.
Neither
var nothing = new System.Void();
(which says I should use void (Not an alias?))
nor
var nothing = new void();
compiles.
It is also not possible to use something like that:
void GiveMeNothing() { }
void GiveMeNothingAgain()
{
return GiveMeNothing();
}
So what's the point with System.Void?

From the documentation:
The Void structure is used in the
System.Reflection namespace, but is
rarely useful in a typical
application. The Void structure has no
members other than the ones all types
inherit from the Object class.
There's no reason really to use it in code.
Also:
var nothing = new void();
This doesn't compile for me. What do you mean when saying it "works"?
Update:
A method void Foo() does not return anything. System.Void is there so that if you ask (through Reflection) "what is the type of the return value of that method?", you can get the answer typeof(System.Void). There is no technical reason it could not return null instead, but that would introduce a special case in the Reflection API, and special cases are to be avoided if possible.
Finally, it is not legal for a program to contain the expression typeof(System.Void). However, that is a compiler-enforced restriction, not a CLR one. Indeed, if you try the allowed typeof(void) and look at its value in the debugger, you will see it is the same value it would be if typeof(System.Void) were legal.

void/System.Void is different from int/System.Int32, it's a special struct in C#, used for reflection only. See this example:
class Program
{
public static void Main(string[] args)
{
Type voidType = typeof(Program).GetMethod("Main").ReturnType;
}
}
There must be some type used to describe the return type of Main method here, that's why we have System.Void.

We have used the following code
public Type GetType(object o)
{
var type = o == null ? typeof(void) : o.GetType();
}
so that we can use the null object pattern. It's pretty good.
This allows us to do stuff like
GetType(o).GetProperties().Select( .....
instead of putting guard clauses everywhere.

Beyond not returning a value, very little definition is given of void (although void* gets some attention) in the language spec. This isn't really a language concern - although the CLI may define it further.
Ultimately though: because it has no meaning to do new void()

Related

Generic method calls another generic with a concrete overload with an out parameter: concrete version is never used

There are several similar questions about generic methods with concrete overloads here on SO and most of them say essentially the same thing: Generic overload resolution is done at compile time so if you want to use a concrete overload, you may need to use dynamic in order to have the runtime decide which overload to use. OK, cool--I understand that. None of the questions I've found deal with an out parameter and I'm wondering if there's a better way to handle this than what I've done. Let's start with the most basic case (my code was all written and tested in LinqPad):
void Main()
{
string x = "";
var g = new GenericTest();
g.RunTest(x); //Ran from TryFoo<T>
g.RunTestWithDynamic(x);//Ran from TryFoo(string)
g.Foo(x); //Ran from TryFoo(string)
}
public class GenericTest
{
//public void RunTest(string withInput) => Foo(withInput); <-- This would fix it
public void RunTest<T>(T withInput) => Foo(withInput);
public void RunTestWithDynamic<T>(T withInput) => Foo((dynamic)withInput);
public void Foo<T>(T withInput) => Console.WriteLine("Ran from TryFoo<T>");
public void Foo(string withInput) => Console.WriteLine("Ran from TryFoo(string)");
}
Here are some things to note:
RunTest is a generic method that calls another generic method, Foo. When I call RunTest, it appears the compiler doesn't follow all the way from the call site to see that g.RunTeset is passing in x which is a string and link it all up so that the Foo(string) overload is called; instead, it just sees that RunTest<T> is calling Foo. It doesn't make different "paths" based on different input values of T. OK, that's fair and understandable.
If I call Foo directly from my Main method, the compiler is smart enough to see that we are calling Foo with a string directly and correctly selects the concrete overload.
As the linked SO posts describe, I can call RunTestWithDynamic which will change which overload is used at runtime based on value. It feels just a bit "hacky", but I'm good with this solution.
I've commented out a line: a concrete overload of RunTest. This would be essentially the same as calling Foo directly. If that were un-commented, it would fix everything. Alas, that is not an option for me in my case.
Now, what if the T is for an out parameter? Consider the pattern used by, say, int.TryParse where you return a bool to indicate if it succeeded or not, but the value you actually want is an out. Now you can't really do dynamic resolution because you can't cast an out parameter. I considered doing something where I make a default(T) and then casting that to dynamic, but if that ever works well anywhere else, there is the problem of reference types that default to null to deal with. Nope, that doesn't work, either.
In the end, the best I could come up with was this:
void Main()
{
string x;
var g = new GenericTest();
g.TryRunTest(out x); //Ran from TryFoo<T>
g.TryRunTestWithDynamic(out x); //Ran from TryFoo(string)
g.TryFoo(out x); //Ran from TryFoo(string)
}
public class GenericTest
{
//This would fix it, but in my case, not an option
//public bool TryRunTest(out string withOutput) => return TryFoo(out withOutput);
public bool TryRunTest<T>(out T withOutput)
{
return TryFoo(out withOutput);
}
public bool TryRunTestWithDynamic<T>(out T withOutput)
{
if(typeof(T) == typeof(string))
{
var retval = TryFoo(out string s);
withOutput = (T)(dynamic)s;
return retval;
}
return TryFoo(out withOutput);
}
public bool TryFoo<T>(out T withOutput)
{
withOutput = default(T);
Console.WriteLine("Ran from TryFoo<T>");
return true;
}
public bool TryFoo(out string withOutput)
{
withOutput = "Strings are special";
Console.WriteLine("Ran from TryFoo(string)");
return true;
}
}
You can see that TryRunTestWithDynamic has to look for the concrete string type specifically. I can't figure out a way to do it so that I can just add overloads and then use dynamic resolution to select the overload I want without having to spell it all out (and let's face it--spelling it all out kind of kills the whole point of having overloads in the first place).
In his post I linked to above (and here for good measure), Jon Skeet mentions using MethodInfo.MakeGenericMethod as an alternative. Here he talks about how to use it. I'm curious if that would help me here, but I can't figure out how to use it with out parameters.
So, here are my specific questions:
While, yes this DOES work, it is VERY clunky. Is there a better way to do this? Most importantly, is there a way I can consume overloads that wouldn't require me checking each type specifically?
Is there a way to use the MethodInfo.MakeGenericMethod route using out parameters and would that help me?
Let's say we could wave a magic wand and all of a sudden a language feature was added to C# that would give us the option to force dynamic resolution for generic methods (either for all cases, or only for the case where the generic parameter is for an out, like my main problem). Taking from the above examples, let's say we had something like this:
//The following are all invalid syntax but illustrate possible
// ways we may express that we want to force dynamic resolution
//For out parameters
public void TryFoo<T>(dynamic out T withOutput){...}
//"dynamic out" could be a special combination of keywords so that this only works
// with output variables. Not sure if that constraint buys us anything.
// Maybe we would want to allow it for regular (not out) generic parameters as well
public void Foo<T>(dynamic T withInput){...}
public void Foo<dynamic T>(T withInput){...}
public void dynamic Foo<T>(T withInput){...}
Let's not focus on the syntax itself; we could easily use a different notation--that isn't the point. The idea is simply that we are telling the runtime that when we get to TryFoo<T>... pause and check to see if there is a different, better fitting overload that we should switch to instead. I'm also not particular on whether we are checking for a better resolution on T specifically, or if it applies to the method in general.
Is there any reason why this might be a BAD thing? As he often does, Eric Lippert makes some interesting points about generic and concrete overloading resolution when inheritance is involved (Jon Skeet is also quoted in other answers, as well) and discusses why choosing the most specific overload isn't always the best choice. I'm wondering if having such a language construct might introduce similar problems.
OK, so I proposed the idea of adding support for opting-in to dynamic binding at the C# GitHub and was given this alternate solution which I like MUCH better than what I am currently doing: ((dynamic)this).TryFoo(out withOutput);
It would look like this:
public bool TryRunTestWithDynamic<T>(out T withOutput)
{
return ((dynamic)this).TryFoo(out withOutput);
}
I will reiterate the warning I was given: this only works for instance methods. In my case, that's fine, but if someone else had a method that was static, it wouldn't help, so the second part of my question (regarding MethodInfo.MakeGenericMethod) may still be relevant.

Can a method use an automatic variable to infer the return type?

IDictionary<int,string> myMethod()
{
var returnVal = ...;
return returnVal;
}
It seems like this is something that should be possible - create a var which automatically takes the method's return type - but I can't find any keyword which would match this. Does it exist?
Creating an object the way you're trying to will not work. A variable's type is determined when it is declared - the compiler doesn't care how you use it (for the most part). So, just because you return it doesn't mean the compiler will automatically infer what the initial type is.
Wjdavis15's answer (which has apparently now been deleted - it made use of generics and initializing the return value to default(T)) kinda sorta works, but it's very limited. It works fine for value types, but reference types the variable will be initialized to null... which is pretty useless unless you're planning on returning null to begin with. Instead, you might be able to do something like so:
private T MyMethod<T>() where T : new()
{
var retVal = new T();
...
return retVal;
}
// Use the method like so:
var dict = MyMethod<IDictionary<int,string>>();
This will work as long as T has a parameterless constructor. The problem with this, of course, is that the method is generic, meaning that it can be used with any class type, not just the one specific class you had in mind. You'd be better off using a non-generic method.
In summary, no, the feature you describe doesn't exist in C#. There are workarounds that are similar to what you want to do, but using them in the way you want is cumbersome and confusing, so it's better you just define what the variable is in the declaration.
If you call the method recursively then you can have a local variable that infers the type of that method's return value.
public static int Foo()
{
var bar = Foo();
return bar;
}
Of course, it forces you to call the method recursively to do so.

Function Parameter type determined at runtime?

Is it in anyway possible ( preferably without using any third party libs), to create a function whose type is determined at runtime in C#?
e.g
public static void myfunc(var x)
{
System.Windows.Forms.MessageBox.Show(x); //just an example
}
NOTE: I want the runtime to determine the type of the parameter and do not want to later cast the parameter to another type, as would be necessary if I use generics. e.g I don't want:
myfunc<T>(T x)
// and then :
MessageBox.Show((string)m);
UPDATE:
I am actually making a function parser for my programming language, which translates to C# code. In my language, I wanted the parameter types to be determined at runtime always. I was looking for some good C# feature for easy translation.
e.g
in my language syntax:
function msg << x
MessageBox.Show x
end
needed to be translated to something that didn't ask for a type at compile time, but would need one at runtime.
e.g
public static void msg(var x)
{
System.Windows.Forms.MessageBox.Show(x);
}
The keyword introduced for runtime binding in C# 4 is dynamic.
public static void myfunc(dynamic x)
This allows you to make assumptions about x that are unchecked at compile time but will fail at runtime if those assumptions prove invalid.
public static void MakeTheDuckQuack(dynamic duck)
{
Console.WriteLine(duck.Quack());
}
The assumption made here is that the parameter will have a method named Quack that accepts no arguments and returns a value that can then be used as the argument to Console.WriteLine. If any of those assumptions are invalid, you will get a runtime failure.
Given classes defined as
class Duck
{
public string Quack()
{
return "Quack!";
}
}
class FakeDuck
{
public string Quack()
{
return "Moo!";
}
}
And method calls
MakeTheDuckQuack(new Duck());
MakeTheDuckQuack(new FakeDuck());
MakeTheDuckQuack(42);
The first two succeed, as runtime binding succeeds, and the third results in an exception, as System.Int32 does not have a method named Quack.
Generally speaking, you would want to avoid this if possible, as you're essentially stipulating that an argument fulfill an interface of some sort without strictly defining it. If you are working in an interop scenario, then perhaps this is what you have to do. If you are working with types that you control, then you would be better served trying to achieve compile time safety via interfaces and/or base classes. You can even use different strategies (such as the Adapter Pattern) to make types you do not control (or cannot change) conform to a given interface.
If you need to know the type... then you need to know the type. You can't have your cake and eat it too.
First off, the cast in your example is unnecessary as all objects implement ToString(). Instead of telling us what you think you need, tell us what problem you are trying to solve. There is almost certainly a solution either via generics or the use of the dynamic keyword (though dynamic is rarely needed), but we need more info. If you add more I'll update this answer.
You could use a type of object or, if you don't know how many items are available, you could use a params object array, i.e. params object[] cParams.

Should an expression of type ‘dynamic’ behave the same way at run-time as a non-dynamic one of the same run-type time?

Consider the following example program:
using System;
public delegate string MyDelegateType(int integer);
partial class Program
{
static string MyMethod(int integer) { return integer.ToString(); }
static void Main()
{
Func<int, string> func = MyMethod;
// Scenario 1: works
var newDelegate1 = new MyDelegateType(func);
newDelegate1(47);
// Scenario 2: doesn’t work
dynamic dyn = func;
var newDelegate2 = new MyDelegateType(dyn);
newDelegate2(47);
}
}
The first one works as expected — the conversion to MyDelegateType succeeds. The second one, however, throws a RuntimeBinderException with the error message:
Cannot implicitly convert type 'System.Func<int,string>' to 'MyDelegateType'
Is there anything in the C# specification that allows for this behaviour, or is this a bug in Microsoft’s C# compiler?
Good catch Timwi.
Our support for dynamic method groups is weak. For example, consider this simpler case:
class C
{
public void M() {}
}
class P
{
static void Main()
{
dynamic d = new C();
C c = new C();
Action a1 = c.M; // works
Action a2 = d.M; // fails at runtime
The d.M is interpreted as a property get (or field access) by the dynamic runtime, and when it resolves as a method group, it fails at runtime.
The same thing is happening in your case, it is just a bit more obscure. When you say MyDelegate x = new MyDelegate(someOtherDelegate); that is treated by the compiler just as if you'd said MyDelegate x = someOtherDelegate.Invoke;. The dynamic runtime piece does not know to do that transformation, and even if it did, it couldn't handle resolving the method group that is the result of the .Invoke portion of the expression.
Is there anything in the C# specification that allows for this behaviour, or is this a bug in Microsoft’s C# compiler?
The spec does not call out that this should be a runtime error, and does imply that it should be handled correctly at runtime; clearly the implementation does not do so. Though it is a shortcoming of the implementation I wouldn't call this a "bug" because we deliberately made the behaviour you've discovered. We did not have the resources to make these kinds of expressions work exactly right, so we left them as errors. If we ever get a good way to represent method groups in the dynamic runtime, we might implement it.
Similarly there is no way in dynamic code to represent the notion of "this dynamic thing is a lambda expression where the types of the parameters are to be determined at runtime". If we have a good way to represent those in the future, we might do the work.
Sam talked a bit about this back in 2008; see his article on it:
http://blogs.msdn.com/b/samng/archive/2008/11/02/dynamic-in-c-ii-basics.aspx
I've run in to this limitation too. Although I couldn't answer the why better than Eric Lippert, there is a straight forward workaround.
var newDelegate2 = new MyDelegateType(x => dyn(x));
It implicitly gets the static signature from the delegate and the dynamic invocation works without any more info. This works for delegates and, as a bonus, dynamic callable objects.

How to do a static cast in C#?

Given a couple types like this:
interface I {}
class C : I {}
How can I do a static type cast? By this I mean: how can I change its type in a way that gets checked at compile time?
In C++ you can do static_cast<I*>(c). In C# the best I can do is create a temporary variable of the alternate type and try to assign it:
var c = new C();
I i = c; // statically checked
But this prevents fluent programming. I have to create a new variable just to do the type check. So I've settled on something like this:
class C : I
{
public I I { get { return this; } }
}
Now I can statically convert C to I by just calling c.I.
Is there a better way to do this in C#?
(In case anyone's wondering why I want to do this, it's because I use explicit interface implementations, and calling one of those from within another member function requires a cast to the interface type first, otherwise the compiler can't find the method.)
UPDATE
Another option I came up with is an object extension:
public static class ObjectExtensions
{
[DebuggerStepThrough]
public static T StaticTo<T>(this T o)
{
return o;
}
}
So ((I)c).Doit() could also be c.StaticTo<I>().Doit(). Hmm...probably will still stick with the simple cast. Figured I'd post this other option anyway.
Simply cast it:
(I)c
Edit Example:
var c = new C();
((I)c).MethodOnI();
Write an extension method that uses the trick you mentioned in your UPDATE:
public static class ObjectExtensions
{
public static T StaticCast<T>(this T o) => o;
}
To use:
things.StaticCast<IEnumerable>().GetEnumerator();
If things is, e.g., IEnumerable<object>, this compiles. If things is object, it fails.
// Compiles (because IEnumerable<char> is known at compiletime
// to be IEnumerable too).
"adsf".StaticCast<IEnumerable>().GetEnumerator();
// error CS1929: 'object' does not contain a definition for 'StaticCast'
// and the best extension method overload
// 'ObjectExtensions.StaticCast<IEnumerable>(IEnumerable)'
// requires a receiver of type 'IEnumerable'
new object().StaticCast<IEnumerable>().GetEnumerator();
Why Use a Static Cast?
One common practice during refactoring is to go ahead and make your changes and then verify that your changes have not caused any regressions. You can detect regressions in various ways and at various stages. For example, some types of refactoring may result in API changes/breakage and require refactoring other parts of the codebase.
If one part of your code expects to receive a type (ClassA) that should be known at compiletime to implement an interface (IInterfaceA) and that code wants to access interface members directly, it may have to cast down to the interface type to, e.g., access explicitly implemented interface members. If, after refactoring, ClassA no longer implements IIterfaceA, you get different types of errors depending on how you casted down to the interface:
C-style cast: ((IInterfaceA)MethodReturningClassA()).Act(); would suddenly become a runtime cast and throw a runtime error.
Assigning to an explicitly-typed variable: IInterfaceA a = MethodReturningClassA(); a.Act(); would raise a compiletime error.
Using the static_cast<T>-like extension method: MethodReturningClassA().StaticCast<IInterfaceA>().Act(); would raise a compiletime error.
If you expected your cast to be a downcast and to be verifiable at compiletime, then you should use a casting method that forces compiletime verification. This makes the intentions of the code’s original developer to write typesafe code clear. And writing typesafe code has the benefit of being more verifiable at compiletime. By doing a little bit of work to clarify your intention to opt into typesafety to both other developers, yourself, and the compiler, you magically get the compiler’s help in verifying your code and can catch repercussions of refactoring earlier (at compiletime) than later (such as a runtime crash if your code didn’t happen to have full test coverage).
var c = new C();
I i = c; // statically checked
equals to
I i = new C();
If you're really just looking for a way to see if an object implements a specific type, you should use as.
I i = whatever as i;
if (i == null) // It wasn't
Otherwise, you just cast it. (There aren't really multiple types of casting in .NET like there are in C++ -- unless you get deeper than most people need to, but then it's more about WeakReference and such things.)
I i = (I)c;
If you're just looking for a convenient way to turn anything implementing I into an I, then you could use an extension method or something similar.
public static I ToI(this I #this)
{
return #this;
}

Categories

Resources