C# - calling one method inside another within the same class - c#

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.

Related

something C# writing multiplying code in static

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 =))

c# cannot access class because of protection level

hey guys I'm new to C# and I was practicing classes and methods and that stuff and I did the following code:
using System;
namespace ConsoleApp6
{
class Book
{
static void Review()
{
int x = 10;
Console.WriteLine(x);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Book.Review);
}
}
}
It's really simple but when i ran it in said that it can't access the "Review" method because of it's protection level, please help
The reason for this error is that the default access modifier for methods is private, which means that only members of the same class can see them.
Since you want to reference the method from another class in the same namespace, you need to give broader access to the method by changing the access modifier to either internal (which means any classes in the same assembly can see it) or public (which means it can be seen by everybody).
Either one of these should solve your problem:
// Only members of the same assembly can access this method
internal static void Review() { // code omitted }
// Everyone can access this method
public static void Review() { // code omitted }
You can read more about access modifiers here.
Additionally, you have set the return value of Review to void, and are then trying to pass this to the Console.WriteLine() method, which expects an actual type. This will result in a compile error (something like: "cannot convert void to [someType]").
In order to solve this you could either just call the method from main and let the method write to the console:
private static void Main(string[] args)
{
Book.Review();
}
Or, my preference would be to have the method return a string, and then write that to the console in the Main method (I prefer this because it makes the method more versatile - someone could call it to simply retrieve a review without displaying it to the console, for example):
public static string Review()
{
int x = 10;
return x.ToString();
}
Note that when you call the method, you will need to include the parenthesis after the name:
private static void Main(string[] args)
{
Console.WriteLine(Book.Review());
}

Call Method based on Type of Parameter

I have an object that can be of type AudioRequest or VideoRequest. Both classes inherit from Request. I have this class:
public static DoThings
{
public static void HandleRequest(AudioRequest r)
{
// Do things.
}
public static void HandleRequest(VideoRequest r)
{
// Do things.
}
}
I want to be able to call DoThings.HandleRequest(r) where r can be either a VideoRequest or AudioRequest and have it call the correct one. Is that possible? I have no control over the *Request classes, so I can't do anything to them. I do have control of the DoThings class and the code that calls HandleRequest. This is the code that calls it, it is WebAPI:
public Response Post(Request input)
{
return DoThings.HandleRequest(input);
}
The code above gives the error Argument 1: cannot convert from 'Request' to 'AudioRequest'.
The original code that I was cleaning up had this:
if (input.GetType() == typeof(AudioRequest))
{
var audioRequest = (AudioRequest)input;
DoThings.HandleRequest(audioRequest);
}
else if (input.GetType() == typeof(VideoRequest))
{
var videoRequest = (VideoRequest)input;
DoThings.HandleRequest(videoRequest);
}
But I figured there was a cleaner way to do this.
Based on the information you've provided so far, your question appears to be a duplicate of How to call a function dynamically based on an object type. I agree with the answer, that the fact that you want to do this suggests you should rethink the design. But, you can use dynamic to accomplish what you want.
Here's a simple console program that demonstrates the basic idea:
class Program
{
static void Main(string[] args)
{
A b = new B(), c = new C();
M(b);
M(c);
}
static void M(A a)
{
WriteLine("M(A)");
M((dynamic)a);
}
static void M(B b)
{
WriteLine("M(B)");
}
static void M(C c)
{
WriteLine("M(C)");
}
}
class A { }
class B : A { }
class C : A { }
The output is:
M(A)
M(B)
M(A)
M(C)
As you can see, in each case the M(A) method is called first, and then the appropriate M(B) or M(C) overload is called from M(A).
In your own example, this could look something like this:
public static DoThings
{
public static void HandleRequest(Request r)
{
// Dynamic dispatch to actual method:
HandleRequest((dynamic)r);
}
public static void HandleRequest(AudioRequest r)
{
// Do things.
}
public static void HandleRequest(VideoRequest r)
{
// Do things.
}
}
Note that dynamic does incur a run-time cost, particularly the first time a method is called with a given run-time type. But depending on the frequency and complexity of these "requests", using dynamic could be the cleanest way out of the current situation.
C# will call the appropriate function that matches the arguments and their types.
That being said, both of your functions accept AudioRequest, I believe one of those should accept a VideoRequest.
public static DoThings
{
public static void HandleRequest(AudioRequest r)
{
// Do things.
}
public static void HandleRequest(VideoRequest r)
{
// Do things.
}
}
If for some reason you must have two different functions that take only AudioRequest you can differentiate between two function with an extra parameter
public static class DoThings
{
public static void HandleRequest(AudioRequest r)
{
// Do things.
}
public static void HandleRequest(AudioRequest r, bool UseAlternativeMethod)
{
// Do other things.
}
}
Simply having a second parameter will call the second method regardless of it's value.
This isn't a best practices solution as you'd rather discriminate between them by accurately renaming the method name to be accurate but in practice you don't always have a choice.

Calling a function from within another function?

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.

Maximizing code readability in methods with side effects?

I'm working with a method that causes side effects on a passed reference parameter. One of my primary concerns for the code is readability, and this is a situation that I feel is a potential cause for confusion.
Take for example:
class Program
{
static void Main(string[] args)
{
var simplePOCO = new SimplePOCO();
// Method 1: causes side effects, but potentially unclear
Method1(simplePOCO);
// Method 2: assignment makes intentions clearer, but unnecessary
simplePOCO = Method2(simplePOCO);
// Method 3: ref/out makes intentions clearer, but (very?) unnecessary
Method3(ref simplePOCO);
// Method 4: avoid the problem altogether
simplePOCO.SimpleProperty = Method4();
}
public static void Method1(SimplePOCO simplePOCO)
{
simplePOCO.SimpleProperty = 1;
}
public static SimplePOCO Method2(SimplePOCO simplePOCO)
{
simplePOCO.SimpleProperty = 1;
return simplePOCO;
}
public static SimplePOCO Method3(ref SimplePOCO simplePOCO)
{
simplePOCO.SimpleProperty = 1;
return simplePOCO;
}
public static int Method4()
{
return 3;
}
}
class SimplePOCO
{
public int SimpleProperty { get; set; }
}
I'm leaning toward using method 2, but I realize it's just using a self-assignment. Method 4 also looks good but in this case will take a little refactoring to get there - is it worth it? I'm curious if anyone has any strong feelings one way or another about this. Obviously, proper naming of the method will go a long way. Are there or some school of thought that addresses this concern? Are there any other styles I haven't thought of?
If this is the only side effect I would put the method were it belongs: inside SimplePOCO so that the method and the data it modifies are encapsulated together:
class SimplePOCO
{
public int SimpleProperty { get; set; }
public void Method5()
{
SimpleProperty = 3;
}
}
Also the method name should indicate that a change is to be expected as a result of the call, i.e. UpdateSimplePropertyRandomly().
I would go with:
public static void Method1(SimplePOCO simplePOCO)
If you return the object, I think it looks as if it's creating a new instance. To me, the void suggests the method is working on my reference that I pass in.
Why cant you create methods against SimplePOCO? Then you'd get
// npn-static
simplePOCO.Method1()
// static
SimplePOCO.Method1(simplePOCO)

Categories

Resources