Calling a function from within another function? - c#

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.

Related

rCannot Explicitly Call Operator or Accessor For Calls From Included Library [duplicate]

I added .dll: AxWMPLib and using method get_Ctlcontrols() but it show error like:
AxWMPLib.AxWindowsMediaPlayer.Ctlcontrols.get': cannot explicitly call operator or accessor
This is my code using get_Ctlcontrols() method:
this.Media.get_Ctlcontrols().stop();
I don't know why this error appears. Can anyone explain me and how to resolve this problem?
It looks like you are trying to access a property by calling explicitly its get method.
Try this (notice that get_ and () are missing):
this.Media.Ctlcontrols.stop();
Here is a small example about how properties work in C# - just to make you understand, this does not pretend to be accurate, so please read something more serious than this :)
using System;
class Example {
int somePropertyValue;
// this is a property: these are actually two methods, but from your
// code you must access this like it was a variable
public int SomeProperty {
get { return somePropertyValue; }
set { somePropertyValue = value; }
}
}
class Program {
static void Main(string[] args) {
Example e = new Example();
// you access properties like this:
e.SomeProperty = 3; // this calls the set method
Console.WriteLine(e.SomeProperty); // this calls the get method
// you cannot access properties by calling directly the
// generated get_ and set_ methods like you were doing:
e.set_SomeProperty(3);
Console.WriteLine(e.get_SomeProperty());
}
}

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());
}

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

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.

Static/Instance methods and extension questions

I'm new to C# and I began working on a project that needed a method added to a class in C#. I found myself re examining the differences between static and instance methods and I'm unable to explain the following in a sample project.
My Core object:
namespace ExtendingObjects
{
public class MyCoreObject
{
public String name;
public String returnName()
{
return name;
}
}
}
My attempt to extend the object:
namespace ExtendingObjects
{
public static class Extensions
{
public static void addName(this MyCoreObject mco, String str)
{
mco.name=str;
}
public static String getName(this MyCoreObject mco)
{
return "test";
}
}
}
Calling program:
namespace ExtendingObjects
{
class Program
{
static void Main(string[] args)
{
MyCoreObject co = new MyCoreObject();
co.addName("test");
//Static method seems to work with instance?
String n = co.returnName();
Console.WriteLine("The name is " + n);
Console.ReadLine();
//Does not work
//Static method from a type
//String n2 = MyCoreObject.getName()
}
}
}
It was my understanding that static items stayed with the class and instance items with the instance per MSDN Static and Instance Members. However, I seem to be able to access a static method through an instance above, but not able to access a static method through a type.
Why does co.returnName() work and not MyCoreObject.getName()? I would think they would be reverse based on my reading. How can I make the getName() method available without instantiating the object first?
Thanks in advance.
Your two methods are extension methods, which are meant to look like instance methods when they're called. They can be called statically, but you need to supply the instance as the first argument, and specify the class which declares the extension method, not the type that the method "extends":
Extensions.getName(co);
When you call an extension method "as" an instance method, it's just a compiler trick. So this code:
co.addName("test");
is compiled to the exact equivalent of:
Extensions.addName(co, "test");
(As an aside, you would do well to start following normal .NET naming conventions as soon as possible. The earlier you get in the habit, the better.)

C# Variable Scope stopping me in my tracks

I'm fairly new to programming. The the constant issue I keep facing when I try anything for myself in C based languages is the scope.
Is there any way to use or modify a variable from within a different method or class? Is there also a way to do this without creating a new intance of a class or object? It seems to wipe the slate clean every time.
Example, I'm setting up a console text game, and I want a different background message to write to the console at certain intervals.
public static void OnTimedEvent(object scource, ElapsedEventArgs e)
{
if(Exposition.Narration == 1)
{
Console.WriteLine("The bar is hot and muggy");
}
if (Exposition.Narration == 2)
{
Console.WriteLine("You see someone stealing beer from the counter");
}
if (Exposition.Narration == 3)
{
Console.WriteLine("There is a strange smell here");
}
}
But I have no way of making different messages play. If I create the variable from within the method it will send that variable to its defult everytime it runs. If I create a new instance of an object or a class, it sends things back to the defult as well. Also, I can't modify a single class when I'm creating new instances of them all the time.
That's just one example of where its been a problem. Is there a way to have a varable with a broader scope? Or am I thinking about this the wrong way?
edit:
To put it simply can I read or change a variable from within a different method or class?
using System;
namespace Examp
{
class Program
{
public static void Main(string[] args)
{
int number = 2;
other();
}
public static void other()
{
if (Main.number == 2)
{
number = 3
}
}
}
}
While I don't think I understood completely your question, you can see here some ways to make a variable "persist" outside a method:
Static variables
Static variables are something like a global variable. You can see them through all the program if you set them as public (if you set them as internal, it's different).
A static variable can be defined as:
class MyClass
{
static int MyVariable = 4;
}
....somewhere...
void MyMethod()
{
MyClass.MyVariable = 234;
}
As you can see, you can access them anywhere.
Variables on heap
If you create an object with new operator, if you keep reference to that object, every modify you do on it, it reflects on all references to that object that you have. For example
class MyClass
{
int X;
}
static class Program
{
static void Main(string args[])
{
MyClass a = new MyClass();
a.X = 40;
Method1(a);
Method2(a);
Console.WriteLine(a.X.ToString()); // This will print 32
}
static void Method1(MyClass c)
{
c.X = 10;
}
static void Method2(MyClass c)
{
c.X = 32;
}
}
You can even use refs to edit your variables inside a method
Basically you misunderstood the concept of "scope", because you question is "which variable types exist" (global/static/local etc.). What you would like to know about scope is this: A local variable exists only within { } where it's defined.
I hope this gives you some suggestion. The answer is definitely not complete but can give you an idea.
Try to be more specific so I can change my answer.
Answer to edit 1:
No you can't change a variable in the way you want, you must add it to the class (Program in this case), try adding:
class Program
{
static int number;
....
}
Obviusly you should remove the one inside the Main method.
Also note that int can't be modified (except without a ref) inside a function if you pass them as parameters because they are copied.
The reason is quite simple: a reference to a Class instance is (at least) the same size as an int (if we are speaking about 32/64 bit systems), so it takes the same time copying it or referencing it.
You can return a value from a method after you have done your calculations if you want, like this:
int x = 3;
x = DoSomethingWithX(x);
int DoSomethingWithX(int x)
{
x += 30;
}
Class access modifiers allow you to control the members that you want the class to expose to other classes. Furthermore, static class with singleton pattern allow use to reuse the same instance across your application.
Looking at your example, it appears that you are simply trying to read the class member, hence a public property in your class should suffice. The instance of this class can be passed while initializing the class in which your OnTimedEvent method is present (this method should be changed to an instance method to access non static members of the your class).
For example,
class MyClass
{
private Exposition exposition;
// Option 1: Use parametrized constructor
// Pass the instance reference of the other class while
// constructing the object
public MyClass(Exposition exposition)
{
this.exposition = exposition;
}
// Option 2: Use an initialize method
public void Initialize(Exposition exposition)
{
this.exposition = exposition;
}
// Remove static to access instance members
public void OnTimedEvent(object scource, ElapsedEventArgs e)
{
// Better to use an enumeration/switch instead of magic constants
switch(exposition.Narration)
{
case HotAndMuggy:
Console.WriteLine("The bar is hot and muggy");;
break;
...
}
}
// Option 3: Use static properties of the Exposition class
// Note this approach should be used only if your application demands
// only one instance of the class to be created
public static void OnTimedEvent_Static(object scource, ElapsedEventArgs e)
{
// Better to use an enumeration/switch instead of magic constants
switch(Exposition.Narration)
{
case HotAndMuggy:
Console.WriteLine("The bar is hot and muggy");;
break;
...
}
}
}

Categories

Resources