new to c#! not too sure why i can't call my method from class
hello! very much new to C# and i've been trying out on how to use constructors in a new class and i can't seem to understand the issue here? although the error is displayed to me but i'm still confused and don't exactly understand as well (i've only learned c# a week or two)
this is my class
8 Replies
and this is the program's
i thought value is given in num1 and num2 in program and it should call the method to do the calculation?
- Your
Addition
method is taking two parameters, which happened to be named the same as your private fields, but are distinct values. Because you named the parameters the same, they're taking precedence over your private fields, causing confusion. If you want to add your two private fields together, you'd just do so, with no parameters for your Addition
method.
- If it is the case that you want to add the private fields together, you wouldn't call Class.Method()
- that would be for a static method, not an instance method. Instead, you'd call instance.Method()
, as in calc1.Addition()
in this case@kav Shawn here hit the nail on the head - you've confused static methods with instance methods. Give it a try and if you need further guidance, feel free to ask 🙂
$static
In C#, static allows you to have members (classes, methods, etc) that are not tied to any particular instance and are therefore always, globally, accessible. When applying
static
members, take the following considerations:
• If there are to be multiple instances of a class, do not use static
• If you need to track state, do not use static
• If you are going to have multi threaded workflows, do not use static unless you're aware of the caveats
static
is best used for stateless methods, extension methods/classes and in areas where you understand the pros/cons. Read more here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/staticthank you so much guys!! helped a lot