I have added the following class to my project
delegate int NumberChanger(int n);
namespace lesson02
{
class Testdelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
}
}
And in my program class under the main method I am trying to create an object of the delegate and assign the method AddNum to it:
NumberChanger nc1 = new NumberChanger(AddNum);
But the AddNum method is not recognized in this class and I get the error message: CS0103 C# The name does not exist in the current context
Can anyone see what I'm doing wrong?
You need to reference the class when making a reference to a static method in a different class. Thus, from (I presume) Program.Main, you should reference Testdelegate.AddNum. EDIT: This presumes you have a using lesson02; reference at the top of your file, or Program exists within the lesson02 or a nested namespace.
Alternatively, if you make multiple reference to static Testdelegate members, you can use a static using (as of C# 6):
using static lesson02.Testdelegate;
Related
I realize this sounds like a question the answer to which can be found in the first google link, but to my surprise it wasn't. I'm learning C# recently and for the first time I'm writing a fairly large project, which at the moment contains more than 200 lines of code and, according to my estimates, should contain more than 1000 in the end.
I understand that this is not a problem for experienced programmers, but I'm starting to get confused.I have found some answers on pulling classes from neighboring files, but my code consists almost entirely of methods and I have not been able to interpret these answers to my advantage. Again, this is most likely due to my inexperience.
i want my files to look something like this:
program1.cs
int x = 25;
program2.cs
Console.Write(x);
As you can see, this does not happen. I have tried adding the CS file either manually or through the solution explorer. Nothing helps, so I really hope to get an answer here. How can I get all methods and variables from one file to work in another in VS? Additional question: If there is no such possibility at all, can I somehow visually hide a piece of my code from myself, just so that it does not bother me until I need to change something in it?
P.S. Yes, I understand that if it is easy to get confused in the code, then the code is poorly composed. I'm also working in this direction, but I would still like to know the answer.
If your class is so big you want to split it into multiple files it’s likely that you should also be splitting it into multiple classes that each perform a simpler job. To access public methods and variables of one class from another class, either they need to be static (meaning there’s only ever one of that thing basically) in which case you can activate them using the name of the class, e.g.:
Class1.cs
public static int x = 25;
Class2.cs
Console.Write( Class1.x );
Or you need a reference to a specific instance of that class, e.g.
Class1.cs
public int x = 25;
Class2.cs
Class1 instance = new Class1();
Console.Write( instance.x );
Ok, so here is the code I promised.
Here are the two files I created
Program.cs
using System;
namespace splitClass
{
// You can either write a class here and use it on the other file
public class HelloThere
{
public HelloThere()
{
Console.WriteLine("Hello, there");
}
public static int add(int a, int b)
{
return a + b;
}
public int subtractFromTen(int c)
{
return 10 - c;
}
static void Main(string[] args)
{
// You can also use the class in the other file
UseHelloThere useHelloThere = new UseHelloThere();
Console.WriteLine(useHelloThere.add(8, 9));
}
}
// or split a class into two using partial keyword
public partial class SomeOtherClass
{
public int abc;
public SomeOtherClass()
{
abc = 87;
}
public int getAbc()
{
return abc;
}
public int add(int b)
{
return b + abc;
}
}
}
Other file.cs
using System;
namespace splitClass
{
// since namespaces are same, you can use the other class from the same file
public class UseHelloThere
{
HelloThere hello;
public UseHelloThere()
{
hello = new HelloThere();
}
public int add(int a, int b)
{
return HelloThere.add(a, b);
}
}
// or you can write the continuation of the other class
public partial class SomeOtherClass
{
public int subtract(int a)
{
return abc - a;
}
}
}
If you want to get all methods and variables from one file to work in another in VS, you can refer to the following steps:
First, define variables and methods in Program1.cs such as:
namespace ConsoleApp7
{
namespace ConsoleApp
{
public static class Program1
{
static void Main(string[] args)
{
}
public static int x = 25;
public static void add()
{
x++;
}
}
}
}
Second, add project reference in Program2.cs.
Finally add using in Program2.cs and then you can use the variables and methods defined in Program1.cs.
using ConsoleApp7.ConsoleApp;
class Program2
{
static void Main(string[] args)
{
Console.WriteLine(Program1.x);
Program1.add();
Console.WriteLine(Program1.x);
}
}
Trying to build and use class library in C#.
Creating class library:
File->New Project->Windows->Classic Desktop->Class Library
Code:
namespace ClassLibrary2
{
public class Class1
{
public static long Add(long i, long j)
{
return (i + j);
}
}
}
Trying to consume it from console application:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ClassLibrary2.Class1 c = new Class1();
c. //no Add function
}
}
}
But c object not contains Add function. Why? How how to fix it?
Add is a static method. You can't call static methods "via" instances in C#. That has nothing to do with it being in a different library.
You can call the method as:
long result = ClassLibrary2.Class1.Add(10, 20);
or if you actually have a using directive for ClassLibrary2 (it's unclear from the question):
long result = Class1.Add(10L, 20L);
Alternatively, change the method to be an instance method, if that's what you wanted - at which point you'd be able to call c.Add(10L, 20L).
You declared Class1 as static, then, you don't need an instance to use it.
ClassLibrary2.Add(1, 1);
Add in static method. You must call it like static method:
Class1.Add(1,2);
If You intent to make it Instance specific remove the static
namespace ClassLibrary2
{
public class Class1
{
public long Add(long i, long j)
{
return (i + j);
}
}
}
In my aspx.cs page I have a int static variable and Im passing it to a constructor of another class, in which I have a function that increments static variable. However, when execution is done and when Im back to my aspx.cs page Im loosing my static variable value.
aspx.cs page
public static int one;
//Im creating an object to test class
Test t = new Test(ref int one);
t.Increment();
Test Class.cs
public class Test {
int _one;
public Test(ref one) {
this._one = one;
}
public void Increment() {
_one++;
}
}
Edit
I have two aspx.cs pages that holds a static variable and a Test class, which has an Increment function, increments the static variables of aspx.cs class. I tried passing by ref when I create an object of Test class but no use. Can someone suggest me best design for this purpose.
one.aspx.cs
public static int one;
//Im creating an object to test class
Test t = new Test(ref int one);
t.Increment();
Two.aspx.cs
public static int Two;
//Im creating an object to test class
Test t = new Test(ref int Two);
t.Increment();
Test Class
public class Test {
int _value;
public Test(ref one) {
this._value = one;
}
public void Increment() {
_value++;
}
}
Your static variable never changes its value. You pass it by reference to the Test constructor, but then you just copy its value to _one. And the change of _one within Increment has no impact on the static variable one.
The problem is here:
int _one;
public Test(ref one) {
this._one = one;
}
Even though you pass a reference to the variable one, you are assigning it's value to this._one. So when you increment you are incrementing the local field and not the reference that was passed in.
Not sure how good this would be but have your Increment function accept the classname as parameter like
public class Test {
public void Increment(string class_name)
{
if(class_name == "One")
One.one++;
else
Two.two++;
}
}
then in your .aspx page call it like
//one.aspx.cs
t.Increment("One");
//Two.aspx.cs
t.Increment("Two");
exe file written in C#
which i need to return a complex return value to another C# project
Here is my code:
class Program
{
private class MyObject
{
private int num;
public int Num
{
get
{
return (this.num);
}
set
{
this.num = value;
}
}
public MyObject(int num)
{
this.Num = num;
}
}
[STAThread]
public static MyObject Main(string[] args)
{
return new MyObject(5);
}
}
this gives me the following error:
...\ConsoleApplication1.exe'
does not contain a static 'Main' method suitable for an entry point.
I've tried playing with it but i got no success in making it return a complex value.
You can't do this from a Main method which is meant to be the entry point of the process.
If you're writing code to be called directly from other code, you should almost certainly be building a Class Library project instead. You can add a reference from one application to another, but it's unusual (at least outside unit tests). If you want to do this, you should just call a different method instead of Main. (You could have a Main method declared that way in one class, and use a different class as the "normal" entry point, but that seems pointlessly complicated.)
As mentioned, if you are invoking your exe as a standalone executable, then Main has to run and all you get is traditional process inputs/outputs.
But you can reference an exe as a library, too, if you really need to.
If this is the code for your exe:
public class MyObject
{
private int num;
public int Num
{
get
{
return (this.num);
}
set
{
this.num = value;
}
}
public MyObject(int num)
{
this.Num = num;
}
}
public class Program
{
public static MyObject DoWork(int num)
{
return new MyObject(num);
}
[STAThread]
public static int Main(string[] args)
{
DoWork(5);
return 0;
}
}
From another exe or dll (assuming you have referenced your first exe) you can invoke the code like this:
MyObject obj = Program.DoWork(8)
This is a very unusual approach, though. If you have libraries which define rich classes/methods that you need in multiple places, you should really put them in a dll.
Going from Java to C# I have the following question:
In java I could do the following:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
I know I can initialize this from the constructor but this does not fit my needs (I want to initialize and call some utility functions without create the object).
Does C# support this? If yes, how can I get this done?
Thanks in advance,
public class Application
{
static int attribute;
static Application()
{
attribute = 5;
} // removed
}
You can use the C# equivalent static constructors. Please don't confuse it with a regular constructor. A regular constructor doesn't have a static modifier in front of it.
I am assuming your //... rest of the code need to be also run once. If you don't have such code you can just simply do this.
public class Application
{
static int attribute = 5;
}
You just can write a static constructor block like this,
static Application(){
attribute=5;
}
This is what I could think of.
In your particular scenario, you could do the following:
public class Application {
static int attribute = 5;
// ... rest of code
}
UPDATE:
It sounds like you want to call a static method. You can do that as follows:
public static class Application {
static int attribute = 5;
public static int UtilityMethod(int x) {
return x + attribute;
}
}
I find something else useful. If your variable needs more than one expressions/statements to initialize, use this!
static A a = new Func<A>(() => {
// do it here
return new A();
})();
This approach is not limited on classes.
-A static constructor doesn't have any parameter.
-A static class can contain only one static constructor.
-A static constructor executes first when we run the program.
Example:
namespace InterviewPreparation
{
public static class Program
{ //static Class
static Program()
{ //Static constructor
Console.WriteLine("This is static consturctor.");
}
public static void Main()
{ //static main method
Console.WriteLine("This is main function.");
Console.ReadKey();
}
}
}
Output:
This is static constructor.
This is main function.