Can you print delegate contents? - c#

i have method where i create random number once called from other class. Making delegate and pointing it to that method invokes that method itself and random number is generated. I can't access that method without creating new random number. I want to get that method returned value with delegate. By writing it "Console.WriteLine(some_kind_delegate);" gives me path "Consoleapp8.class+method".
P.S although when i use delegate when comparing his pointed value with other variable answer is correct.
Screenshot in visual studio environment with my comments: https://www.dropbox.com/s/cx6858x5qen7k1p/dayum.PNG?dl=0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp8
{
abstract class variklis
{
delegate int delegatas();
static int litrazas;
static void Main()
{
Console.WriteLine("serijinis bloko numeris: " + blokas.serijinis_bloko_numeris());
Console.WriteLine("variklio tipas: In-line " + blokas.vidus() + " cilindrai");
Console.WriteLine("stumokliu skaicius: " + stumokliai.stumokliuskaicius);
Console.WriteLine("stumokliu kodas: " + stumokliai.stumokliu_kodas());
Console.Write("galimas variklio litrazas siam automobiliui: ");
int.TryParse(Console.ReadLine(), out litrazas);
litrazui();
}
public static void litrazui()
{
string damm;
delegatas zeta;
zeta = blokas.litrazas;
Console.WriteLine(zeta);
if (zeta() <= litrazas)
{
damm = "variklis tinkamas siam automobiliui";
}
else
{
damm = "variklis netinkamas siam automobiliui";
}
Console.WriteLine(damm);
}
}
}

The problem is due to the Console.WriteLine implicitely converting the delegate to a string, which is Consoleapp8.class+method, instead you need to invoke the function be appending parenthesis to the end of it.
Console.WriteLine(zeta());
And to answer the question in your comment. If you need to store the int that is the return from the delegate you can do apply the same principle from above, by appending parenthesis to invoke the function.
int number = zeta();

Related

Getting error: Cannot implicitly convert type 'string' to 'int'

I'm new to coding. I am trying to improve myself by making simple coding. I just encountered such error while writing a code to retrieve data from user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FuelCalc
{
internal class Program
{
static void Main(string[] args)
{
//readline
Console.WriteLine("Lütfen size hitap edebilmem için adınız ve soyadınızı giriniz...");
string namesurn= Console.ReadLine();
Console.WriteLine("Merhaba " + namesurn +" lütfen aracınızın ortalama yakıt tüketimini giriniz...");
int yakit = Console.ReadLine();
Console.ReadLine();
}
}
}
What you could try is adding a loop to repeat until the user enters a number. The int.TryParse method will return true if the string returned from Console.ReadLine() can be interpreted as an int and you will have a value for yakit in that case. Otherwise, ask the user to try again.
(I'm relying on Google Translate here leave me a comment if I did something wrong!)
static void Main(string[] args)
{
//readline
Console.WriteLine("Lütfen size hitap edebilmem için adınız ve soyadınızı giriniz...");
string namesurn = Console.ReadLine();
Console.WriteLine("Merhaba " + namesurn + " lütfen aracınızın ortalama yakıt tüketimini giriniz...");
// Loop until a valid int is received.
while(true)
{
if(int.TryParse(Console.ReadLine(), out int yakit))
{
Console.WriteLine($"{yakit} alınan");
break;
}
else
{
Console.WriteLine("Numara gerekli");
}
}
Console.ReadLine();
}
You may want to consider float or double instead of int in case the user enters a decimal point character like "40.9" in which case you could substitute:
float.TryParse(Console.ReadLine(), out float yakit)

for loop and string slicing gives unexpected output

i am starting to learn C#, my first language i learned is Python and i switched to Visual Studio Code for it from Pycharm.
I am trying to code a simple TicTacToe as exercise, when i loop trough my TicTacToe grid to see if one of the empty fields marked with numbers is still avaliable, i get an unexpected output.
The expected output would be 1-9, but its not, i am not allowed to post images so not sure how to say/show it.
When i use char as data type the correct value seems to be there in '' as second value, but how do access it?
in both cases comparision operator do not yield the expected results!
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CSharp_Shell
{
public static class Programm
{
static int meow = 1;
static string board_roof = "-------";
static string board_mid1 = "|1|2|3|";
static string board_mid2 = "|4|5|6|";
static string board_mid3 = "|7|8|9|";
static string board_all_default = board_roof + Environment.NewLine + board_mid1 + Environment.NewLine +board_mid2 + Environment.NewLine +board_mid3 + Environment.NewLine + board_roof;
public static void Main(string[] args) {
Acces_board2(meow);
}
public static void Acces_board2(int lfm) {
for(int gas=0; gas<board_all_default.Length; gas++) {
bool result = char.IsNumber(board_all_default[gas]);
if (result) {
Console.WriteLine($"{board_all_default[gas]} , {lfm}");
if(lfm < board_all_default[gas]) {
Console.WriteLine($"True");
}
}
}
}
}
}
doesnt matter if i use
if (lfm < board_all_default[gas])
or
int checkme = board_all_default[gas];
if (lfm < checkme)
it never works, that would be no issue in python, i have no clue whats happening

Skype issue with multiple params

I am trying to make a C# Stress script but it keeps giving me the error: Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using Skyper;
using SKYPE4COMLib;
using System.Net;
namespace Skyper.plugins
{
public static class Help
{
public static string Description
{
get
{
return "Stresser";
}
}
public static void Execute(string[] Params, int chat, string username)
{
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=" + Params[1]));"&port=&time=&method=";
}
}
}
How this script will work is users in Skype will type in !stress ip, port, time, method and then it will submit it to the API.
Following is a simple string, which is not assigned to any thing,
"&port=&time=&method=";
So may be you can use something like:
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=&port=&time=&method=" + Params[1])");
or change that string properly with double quotes and brackets end symbols

Use method to Return value int in C#

I'm taking a programming class in c# and it is our first week and I'm trying to work ahead a little. To that end, I am trying to rework one of our class labs and am stuck with my 'GetInt' method.
Ideally, the GetInt method (line 50) takes in a string (Enter a number) and returns the number as an int so i can then use it to do some math. Currently line #24 turns the test error 'Cannot implicity convert type 'int' to 'string'.
Any help is appreciated. I am very much a newb, so please don't assume i know anything.
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lec022_If_statement_int
{
class Program
{
//Set to public so it is visible
//void because it returns nothing
//Play is a method within the class Program I've added
public void Play()
{
DisplayStr("Lecture 2c | If Statements with ints");
DisplayReturns();
DisplayStr("Welcome to Dunut King");
DisplayReturns();
//Collect User Name
//GetString converts to lower, trims
String numDonuts = GetInt("How many donuts would you like?: ");
DisplayReturns();
//Display welcome
Console.WriteLine("You asked for " + numDonuts + " donuts.");
DisplayReturns();
DisplayReturns();
DisplayStr("Have a great Day!");
}
//MaxBox 2.0
public void DisplayStr(String StrTxt)
{ Console.Write(StrTxt); }
public void DisplayReturns()
{ Console.Write("\n\n"); }
public string GetString(String StrVar)//note - using strings here
{
Console.Write(StrVar);
return Console.ReadLine().ToLower().Trim();
}
public int GetInt(string intVar)//note - using ints here
{
Console.Write(intVar);
return int.Parse(Console.ReadLine());
}
//Initiate Program
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.Read();
}
}
}
Your GetInt method returns int. So you need to change from
String numDonuts = GetInt("How many donuts would you like?: ");
to
int numDonuts = GetInt("How many donuts would you like?: ");
The problem is that the method GetInt returns int.
And you're trying to assign its return value to this String variable on line 24.
String numDonuts
You cannot do this.
Change the first word on line #24 from 'String' to 'int' because I am asking for an int not a string.
Your problem is there:
String numDonuts = GetInt("How many donuts would you like?: ");
You try to set int value to string variable.
change to
var numDonuts = GetInt("How many donuts would you like?: ");
Your GetInt method returns integer type so you should use an integer type to store it, not a string.
Here is the fixed code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lec022_If_statement_int
{
class Program
{
//Set to public so it is visible
//void because it returns nothing
//Play is a method within the class Program I've added
public void Play()
{
DisplayStr("Lecture 2c | If Statements with ints");
DisplayReturns();
DisplayStr("Welcome to Dunut King");
DisplayReturns();
//Collect User Name
//GetString converts to lower, trims
int numDonuts = GetInt("How many donuts would you like?: ");
DisplayReturns();
//Display welcome
Console.WriteLine("You asked for " + numDonuts + " donuts.");
DisplayReturns();
DisplayReturns();
DisplayStr("Have a great Day!");
}
//MaxBox 2.0
public void DisplayStr(String StrTxt)
{ Console.Write(StrTxt); }
public void DisplayReturns()
{ Console.Write("\n\n"); }
public string GetString(String StrVar)//note - using strings here
{
Console.Write(StrVar);
return Console.ReadLine().ToLower().Trim();
}
public int GetInt(string intVar)//note - using ints here
{
Console.Write(intVar);
return int.Parse(Console.ReadLine());
}
//Initiate Program
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.Read();
}
}
}
I've just tested the program. You enter a number and you get a response. Works nicely. (For it's simple purpose :-) )

print_r() PHP function in C#

So I'm trying to write a C# function print_r() that prints out information about a value passed much in the same way that the PHP print_r() function works.
What I'm doing is taking in an object as an input in to the function, and depending on what type it is, I'll output the value, or loop through an array and print out the values inside the array. I have no problem printing out basic values, but when I try to loop through the object if I detect it is an array, I get an error from C# saying "Error 1 foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'".
Now I'm assuming this is just because object doesn't implement IEnumerable<>, but is there any way that I can process this taking in the input as type object?
This is my current code for the function (the IEnumerable<> part is blank in terms of content, but this is the code that is giving me an error.
Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void print_r(object val)
{
if (val.GetType() == typeof(string))
{
Console.Write(val);
return;
}
else if (val.GetType().GetInterface(typeof(IEnumerable).FullName) != null)
{
foreach (object i in val)
{
// Process val as array
}
}
else
{
Console.Write(val);
return;
}
}
static void Main(string[] args)
{
int[] x = { 1, 4, 5, 6, 7, 8 };
print_r(x);
Console.Read();
}
}
}
val is declared as an Object. After checking if it's an IEnumerable (which you can do simply with is, as shown, but this works also with your original code) you have to cast it explicitly
else if (val is IEnumerable)
{
var e = val as IEnumerable;
foreach (var i in e)
{
Console.WriteLine(i.ToString());
}
}
There is LINQPad that has Dump() extension method, but you can use it only in LINQPad
We can write our own extension method to dump any object to html and view it in browser.
You need to reference LINQPad.exe
public static class Extension
{
public static void Dump<T>(this T o)
{
string localUrl = Path.GetTempFileName() + ".html";
using (var writer = LINQPad.Util.CreateXhtmlWriter(true))
{
writer.Write(o);
File.WriteAllText(localUrl, writer.ToString());
}
Process.Start(localUrl);
}
}
You would have to use reflection to do this I think, I want a similiar function and ouputted my objects into tables using reflection.
I dont have the code to hand but found the basis of my solution here!

Categories

Resources