first of all, i apologize if this question has already been asked. This is my first time asking something on stackoverflow.
so, i am currently learning C# and decided to write a piece of code for practise.
this monstrocity is the result:
static class Calculator
{
public static int multiply;
public static int Sum(int times1, int times2)
{
multiply= times1 * times2;
return multiply;
}
public new static string ToString()
{
return $"this is the result of a calculation/multiplication: {multiply}";
}
}
pretty neat right? its supposed to return a simple multiplication and print it in the main string using an override ToString method (but since that cant be done in static, I made a new one and used that).
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(Calculator.ToString());
}
}
this is where the problem comes into play, because the console simply states:
this is the result of a calculation/multiplication: 0
even when i assign values to 'times1' and 'times2' the result is the same.
I cant figure out what I am doing wrong here, can anybody help me out?
Multiply doesn't contain a value. First call Sum function with whatever numbers you want to multiply and then you can write the result.
class Program
{
public static void Main(string[] args)
{
Calculator.Sum(2, 4);
Console.WriteLine(Calculator.ToString());
}
}
it's due to the static keyword. So, basically, your new static method ToString()(is not the best name) knows nothing about multiply returned after Sum execution,
Do not use static at all
Perform calculation directly in ToString()(suggest to rename =))
Related
I have been spending a lot of time trying to find a library that allows to log information about the methods that are being executed. Somehow I feel that all of them are too invasive. Is there any library or code that makes this so simple that I only need to add a decorator/attribute to the method?
Here what I would like to have:
internal class Calculator
{
[CustomInterceptor]
public static int Add(int a, int b)
{
return a + b;
}
}
internal class CustomInterceptor : Attribute
{
//here some implementation
}
static void Main(string[] args)
{
var result = Calculator.Add(10, 2);
Console.WriteLine($"Result : {result}");
}
Desired output
Before Add
Result 12
After Add
If this can be done with Reflection, please I would prefer that approach since that would imply no need for third party libraries.
Thanks in advance.
I have 2 methods:
static int CalculateParity(string encodedHamming, int parityBit)
{
//Code here
}
static string CalculateHamming(string rawByte)
{
//Code here
}
Inside the main method (all of these are in the same class) I want to call the first two methods. I understand normally it would be
CalculateHamming();
CalculateParity();
To call them, however I'm not sure how to call them because the methods have definitions. I had a look around stack overflow and other sites but I can't find anything. If someone could explain to me how to do this or link me to something similar I may have missed that would be great, thanks!
You have to use ClassName.MethodName so if the class was called Calculations, like below:
static class Calculations
{
static int CalculateParity(string encodedHamming, int parityBit)
{
//Code here
}
static string CalculateHamming(string rawByte)
{
//Code here
}
}
Inside main would be like:
main()
{
string rawBtye;
Calculations.CalculateHamming(rawBtye);
}
If you want to call CalculateParity inside CalculateHamming you don't need the ClassName before:
static string CalculateHamming(string rawByte)
{
CalculateParity(encodedHamming, parityBit);
}
I think you should first get some clue about the basic concepts.
here methods/functions
and here classes
Your program's structure should be something similar to this:
class Program
{
static void Main(string[] args)
{
}
void Function1()
{
}
void Function2()
{
}
}
Nonetheless, I advise you learning the concepts first, then solving your particular issue.
Trying a shot to a little advanced text adventure here, I have an inventory class. (isn't an error) and it all works great!
I'm trying to implement a feature of an input. That it just leads to input, and then returns the arguments back to that class. I thought it would be easy. Turned out a 'void' method can't return something. I don't know what I should use then.
I searched a bit on Google but can't find google, and the answers on here are all XML or more experienced programmers. There are also a few simpler once, but those are unanswered.
This is my Program class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inventory_system_test
{
class Program
{
//Objects
static private Inventory inv = new Inventory();
//strings
static private string args;
//variables
static void Main(string[] args)
{
Write("Do you want to kill dave?");
input();
}
static public void input()
{
bool done = false;
Writen("Enter a command: ");
args = Console.ReadLine();
while (!done)
{
if (args.Contains("add inv "))
{
args = args.Split()[2];
inv.additem(args);
}
else if (args.Contains("remove inv "))
{
args = args.Split()[2];
inv.removeitem(args);
}
else if (args.Contains("see inv"))
{
Write("INVENTORY:");
inv.getinv();
}
else if (args == "close")
{
Environment.Exit(0);
}
else
{
done = true;
return args; ///**Here is the error ofcourse.**
}
}
} //Input files things :)
#region Easy Commands (Write, Sleep)
//Write to console
public static void Write(string writev)
{
Console.WriteLine(writev);
}
//Sleep for 'int sleeptime' in milliseconds
public static void Sleep(int sleeptime)
{
System.Threading.Thread.Sleep(sleeptime);
}
public static void Writen(string writen)
{
Console.Write(writen);
}
#endregion
}
}
I'm getting to understand scripting more and more, and that's just by asking question and searching Googles, I really love the people on Stackoverflow! Thank you all for your help!
So uh.. how would I go and do this?
There aren't many methods.. And I wouldn't know what to do from here.
Turned out a 'void' method can't return something. I don't know what I should use then.
You should use a method which is declared to return the kind of information you want to return! When a method is void, that specifically means it's not meant to return anything.
In this case it looks like you're trying to return the value of args, which is a string variable, so you want:
public static string input()
Additionally:
You should follow .NET naming conventions
There's no reason for your args variable to be static - it would better as a local variable within your method
args is an odd name for this variable anyway, in my view. Given that you're asking for a command, why not use command as the variable name?
I suggest you read the MSDN page on methods or look in a good book about C# to learn more about return types, parameters and so on.
From void (C# Reference)
When used as the return type for a method, void specifies that the
method does not return a value.
But your input method returns a value so..
Console.ReadLine() methods retursn a string so your args is looks like a string. That's why you should change your return type as a string like;
public static string input()
{
}
You declare args as being of type string, so that's what you should return:
static public string input()
{
...
return args;
}
I have seen numerous posts debating about overloading a method by changing its return type, but, the following program should ideally work fine, because the variable i of type integer can only hold integer values.
So, it should ideally call the function int print(int a) function and not even look at the function float print(int a) because it returns a float value, and in main(), I have used an integer variable to hold the value returned by the method, and an integer variable can never hold a float value ..
The following code demonstrates it →
class temp
{
public float print(int a)
{
int l=12.55;
return l;
}
public int print(int a)
{
int p=5;
return p;
}
}
class Program
{
static void Main(string[] args)
{
temp t=new temp();
int i=t.print(10);
A.Read();
}
}
In other scenario, where I do something like this →
class temp
{
public float print(int a)
{
int l=12.55;
return l;
}
public int print(int a)
{
int p=5;
return p;
}
}
class Program
{
static void Main(string[] args)
{
temp t=new temp();
float f=t.print(10);
A.Read();
}
}
Here, I accept that the compiler should generate an error, because it falls in a dilemma whether to call public int(int a) or public float(int a), and because a variable of type float can holding both integer and float values ..
There is no return-type overloading in c#. What if you had ignored the return value, or assigned it to an Object? Then which overload would be called? There are so many ambiguous scenarios, this would be nearly impossible to implement.
It's not because of that, it's because of other scenarios.
For example, you know when you call Console.ReadLine() just to wait for user input? (e.g. press enter to continue)? Well, you could do the same with your print method in this case. Which one should it call then? Should it call the float method? Should it call the int method? What happens when they use var? dynamic? Generics?
You could argue that it should compile in your case, because you're not using it like that. However, what if it's in a class library? What if it's called through reflection? You can't just spend half of the compile-time checking whether it will be called anywhere else, without the return type.
And also, it wouldn't be good practice. You couldn't easily tell them apart, so you could cause so many bugs with this.
So in short: it's possible, but it's so, so impractical it would never be considered as wanted by language designers[1].
[1]: Interesting sidenote, MSIL allows it. So if you used ildasm, you could get return type overloading. Mainly because to call a function in it, you need to do this: call MyReturnType MyFunc(MyType, MyOtherType)
say you had
int foo(int a){..}
double foo(int a) {...}
and then called
foo(1);
or var x = foo(1);
So which one did you mean to be called?
Trying to cope with the former would mean the compiler would have to figure out how the function was being called in the first case, the second is crossed fingers time.
Aside from that being PIA for the language designer what about the programmer? Seeing as it's easily corrected with fooInt, and FooFloat, why would anyone choose the extra level of complexity (not to mention performance with late binding) in favour of a more meaningful name?
The whole point of a strong and statically typed language is to remove this sort of ambiguity at compile time.
I want to use a function from another class within a new function which I will call from main. I am trying to do this as below, but get an error:
Error The name 'Class1' does not exist in the current context.
Actually, in my code I use different names, but its just to illustrate the structure and to make it easier to read for you.
public class Class1
{
public static int[] Function1()
{
// code to return value
}
}
public class Class2
{
public static int Function2()
{
int[] Variable = Class1.Function1();
//other code using function1 value
}
}
Actually, in my code I use different names, but its just to illustrate the structure and to make it easier to read for you.
Unfortunately you've made it so easy to read that you have eliminated the problem entirely! The code you posted does not contain an error and is perfectly valid.
The error message is very clear; from wherever you are actually calling the code, "Class1" (or whatever it may be) is not in scope. This may be because it is in a different namespace. It may also be a simple typo in your class name. Does your code actually look something like this?
namespace Different
{
public class Class1
{
public static int[] Function1()
{
// code to return value
}
}
}
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
// Error
var arr = Class1.Function();
// you need to use...
var arr = Different.Class1.Function();
}
}
}
That's the best I got until you post the actual code.