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);
}
}
}
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);
}
}
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;
I have a C# project, and I want to use the function of my project in matlab.
I've added
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
befor every classes in my project and make the out put type class library.
but when I use of dll in matlab,
temp = NET.addAssembly('../../foo')
and then foo.Classes, there is no class!
what should i do?! plz help me :)
Sample regarding above comment
To use a class from a .NET assembly using NET.addAssembly(...), there is no need to make the class COM Visible but the class, as well as the methods you want to access to, have to be public.
.NET code
namespace foo
{
public class SampleClass
{
// Constructor
public SampleClass() { }
// Static example
public static string StaticMethod() { return "Hello from static method."; }
// Instance example
public string InstanceMethod() { return "Hello from instance method."; }
}
}
Usage from Matlab
% Loading the .NET assembly
NET.addAssembly('..\..\Foo.dll');
% Call of a static method
foo.SampleClass.StaticMethod()
% Call of an instance method
instance = foo.SampleClass();
instance.InstanceMethod();
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.
I'm working with a class library in C# with its own methods and I want to create an array from this library, but I when call it in the main program I cant see its methods.
public class ClassLibrary1
{
public int num;
public ClassLibrary1 ()
{
}
public void Readdata()
{
Console.Write("write a number ");
num = int.Parse(Console.ReadLine());
}
}
program.cs :
ClassLibrary1[] arraynumbers = new ClassLibrary1[5];
arraynumbers.Readdata();
And I can't use Readdata().
Can anyone help me?
If you want to call methods in your class, you'll have to create at least one instance. As it is, all you've done is create an array of null references, and then attempt to call your method on the array. Here's one way you could do it.
ClassLibrary1[] arraynumbers = new ClassLibrary1[5];
for(int i = 0; i < 5; i++)
{
arraynumbers[i] = new ClassLibrary1();
}
arraynumbers[0].Readdata();
You can't use Readdata the way you've put it because ClassLibrary1[] is an ARRAY object, not a ClassLibrary1 object, in which your method is defined.
You'd have to do something like this instead:
arraynumbers[0].Readdata();
Readdata() is a method of the ClassLibrary1 instance, not the array that holds ClassLibrary1 instances.
Methods that are defined on a class may not be called on a collection of that class. If you want to use a method on a collection, consider making an extension method:
public static class ClassLibrary1Extensions
{
public static Readdata(this ClassLibrary[] value)
{
...
}
}
The "this" keyword in the first parameter allows you to "pretend" this method is on a type of "ClassLibrary1[]" or array. I.e. extending that type.