Console.WriteLine() error CS1503 cannot convert from 'void' to 'bool' - c#

I am executing this simple program in which I am trying to see the outcome of Console.WriteLine with function returning void given as an argument.
using System;
class Program
{
static void printMe()
{
}
static void Main(string[] args)
{
Console.WriteLine(printMe());
}
}
This is giving following error:
Program.cs(11,27): error CS1503: Argument 1: cannot convert from 'void' to 'bool' [C:\Users\Nafeez Quraishi\source\repos\X\X.csproj]
The build failed. Fix the build errors and run again.
As per the WriteLine documentation at https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=netframework-4.8
this looks to be corresponding to following case:
WriteLine(Object)
Writes the text representation of the specified object, followed by
the current line terminator, to the standard output stream.
Question is:
In order to write text representation of the function object returning void, why is it trying to covert it in to bool(than perhaps string)?

the void is treated specially by C# language and .net runtime. so a user can not create an instance of void by static way or dynamic way.
Now come to your question about why it converts into bool and not in the string.
if you run below code in unsafe assembly. you can see it has size of 1 byte.
this lead to convert into bool and not string
static unsafe void Main(string[] args)
{
//Console.WriteLine(sizeof(System.Void));
var o = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(void));
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(o));
Console.Read();
//Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(System.Void));
}

How do you print one void (obviously means 'void'-nothing, not even null)? You must return something, not 'void'
If you want, you can do
static bool!!!!! printMe() //Hi I'm a function returning a value, bool precisely.
{
return false; //I must return something.
}
Edit: you want the signature of the function/method?
You want Reflection. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
static void Main()
{
MethodInfo[] mInfo= typeof(TheClass).GetMethods();
//now you can enumerate the methods, and know everything about them, even run them
}
Welcome to new way to use C#, there are so many space, get in.

Related

Could not use Delegate's Method Property in C#?

When i try to use Delegate's Method Property in C# i get this error.
'myDelegate' does not contain a definition for 'Method' and no
extension method 'Method' accepting a first argument of type
'myDelegate' could be found (are you missing a using directive or an
assembly reference?)
I really don't know the reason why i get this. My program is fairly simple and is based on delegates. Below it's code is given:
public delegate void myDelegate(int x);
public class Program
{
public void Main(string[] args)
{
X x = new X();
myDelegate d = x.InstanceProgress;
Console.WriteLine(d.Method);
}
}
class X
{
public void InstanceProgress(int percent) => Console.WriteLine(percent);
}
I get error on this line:
Console.WriteLine(d.Method);
See this image below, although i get the proper output but i get the error.
I have marked the error with green arrow on the image.
Looking at OP's screenshot. That looks like a Visual Studio error. And since it lets you build the it's not a true error. I don't get that error in VS2015.
I'd clean the solution and restart visual studio. That should clear it.
Old:
You'll want to do something like this:
X x = new X();
myDeligate d = x.InstanceProgress;
d.Invoke(5);
// or as Rahul pointed out you can simply use
d(5);
Invoke() is what actually calls the method. Until then the delegate is just a pointer to the method that you want to call.

How to add to a class a string with two integers and show the sum

Greeting fellow programmers!
I am currently studying software development (I started not a month ago) and I have a problem that needs a solution. Underneath you can find the code and as you can see, the method WriteNumber needs help. I need to write the code in a way that when I run the program, on the console screen the following two lines will be shown:
Hello World!
81
The Main method code cannot be changed and also I cannot add more methods to the class Calculator so the code needs to be done only within the WriteNumbers method. I have tried a lot of things but I am still grasping how everything works so any help is welcome! Thank you in advance for your time.
Namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber()
{
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
Not to do your homework for you to just be copied/pasted, hopefully I can give you some hints...
Notice how the method is being invoked:
Calculator.WriteNumber(53 + 28)
The 53 + 28 part happens first, then the result of that operation is passed to the method. That result, naturally, is 81. What's important about that is its type, which is an integer.
So, reasonably, the method signature needs to accept an int as a parameter. This would be done very similarly to how the other method accepts a string as a parameter:
public static string WriteText(string input)
What, then, does that method need to do with that input? Well, it's only a single value, so there aren't any calculations to be performed on it. It would appear that the method simply needs to return the value as a string. (It's your homework so you tell me, is that correct?)
This can be done with exactly two things:
Calling .ToString() on the value
Using the return keyword to return the result of that operation
(Note: The .ToString() operation does something very intuitive on value types, such as int or double or bool. As you progress into using reference types, you're going to find that it does something very different. Any time you have a custom class on which you want to call .ToString(), you'll need to override the .ToString() method on that class first.)
Please read David's answer, it's important that you make the effort to understand why this works the way it does. That being said:
public static string WriteNumber(int number)
{
return number.ToString();
}
Thank you all for your valuable input but special thanks to David because he showed where I made my error. I forgot that the two numbers in the main function will be summed up FIRST and THEN forwarded to the method in the class Calculator. After that got cleared up, it was easy to understand what to do (basically adjust the type of the input parameter to int).
namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber(int sumOfNumbers)
{
return "" + sumOfNumbers;
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
}

Rename existing method returning void with input arguments

Maybe this is silly, but I'm trying to shorten the calling of the method StreamWriter.WriteLine becasue I have to call it many times throughout my code. So, instead of calling myFile.WriteLine() I would like to write just myFile.WL().
Is this possible?
After searching for a solution I wrote this:
private static void WL(this StreamWriter myFile, params string myString)
{
return (void)myFile.WriteLine(myString);
}
but I get the error
Cannot convert type 'void' to 'void'
Any ideas?
There is no need for the extension method, but just for the sake of completeness...
Remove the return statement from your method, as it doesn't have to return anything.
private static void WL(this StreamWriter myFile, params string myString)
{
myFile.WriteLine(myString);
}
BUT, Reconsider what you are trying to do. There is no point in shortening WriteLine to WL, it doesn't serve any purpose, it will make the code less readable, also you will not be able to cover up all the overloads.
Your Extension method should only be
private static void WL(this StreamWriter myFile, params string myString)
{
myFile.WriteLine(myString);
}
Reasons:
WriteLinemethod of StreamWriter does not return anything i.e. void. It only and I quote Writes a string followed by a line terminator to the text string or stream. So you should remove return keyword from the method. Read here.
BTW, Extension method should probably be public if you want to use it outside of the class you define it in.

C# generic delegate that accept function without arguments

I've created a generic delegate and I want to assign to it a function without any arguments.
Is it possible?
Here is what I tried so far:
class Program
{
public delegate void TemplateDel<T>(T item);
public static void fWriteLetters(char[] p_cLetters)
{
for (int i = 0; i < p_cLetters.Length; i++)
Console.WriteLine(p_cLetters[i]);
}
void fNoArg()
{
Console.WriteLine("No arguments!");
}
static void Main(string[] args)
{
TemplateDel<char[]> l_dWriteLeters = new TemplateDel<char[]>(fWriteLetters);
TemplateDel<void> l_dNoArg = new TemplateDel<void>(fWriteLetters);
}
}
the last line of code doesn't compile...
No it is not possible.void is only valid in return types.You can't use it as a type in other contexts. (except the unsafe context)
You need add another overload for your delegate.
public delegate void TemplateDel();
Or simply use an Action.
As Selman22 notes in the other answer:
No it is not possible.
But there is another way, use a lambda to throw away the argument:
TemplateDel<bool> l_dNoArg = new TemplateDel<bool>(_ => fWriteLetters);
(Using _ as the identifier here matches F#'s wildcard – ignore this argument – syntax.)
While not helpful here, this kind of wrapper is helpful when arguments are not interested in are passed and saves writing an extra member just to ignore or re-arrange arguments.

Assign extension methods to a variable

I am trying to assign a variable to an extension method, but getting the error when I hover over the line.
cannot assign 'void' to an implicitly-typed local variable
I am checking for empty fields and calling my extension method and wanted to check more than one field and if they were all failing I wanted them to appear in one error box instead of them piling up.
if (drp_SelectGroup.SelectedValue == "0")
{
var message = this.ShowMessage("Select an Ethnic Group", "ERROR", ErrorType.error);
}
Edit*
public static void ShowMessage(this Page page, string message, string title, ErrorType err)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "toastr",
String.Format("toastr.{0}('{1}','{2}');", err, message, title), addScriptTags: true);
}
The problem isn't that it's an extension method - it's that the extension method has a void return type. Presumably that method shows the message, rather than just creating it. You'd get exactly the same error message if you tried to call any other void method and assign the result to a variable.
You probably need to change your extension method to something like this:
public static string GetMessage(this Whatever foo, string message, string type,
ErrorType errorType)
From the error it looks like ShowMessage has a void return type.
That means that it isn't returning anything.
You are trying to assign that nothing type to a variable.
Solution:
Change the signature of ShowMessage to return what you need it to return.
The return type of this method is: void. You can not assign a type void to a variable.
this.ShowMessage("Select an Ethnic Group", "ERROR", ErrorType.error);
appears to have a return type of void. You cannot then assign to a local variable (var message)
You can change the return type of Show.Message() and this should work for you.

Categories