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.
Related
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);
}
}
}
I'm making c# app where I need to access method in partial class from another class.
To be more specific I want to add items to listview from class that is different from partial class but in same namespace.
I tried like this:
public partial class Aa : Form
{
public static void UpdateListView(string[] array)
{
if (ProcessNetUsageList.InvokeRequired)
{
ProcessNetUsageList.Invoke(new Action<string[]>(UpdateListView), array);
}
else
{
ListViewItem item = new ListViewItem(array[0]);
for (int i = 1; i < 4; i++)
item.SubItems.Add(array[i]);
ProcessNetUsageList.Items.Add(item);
}
}
}
and then access it from another class like:
class Test
{
test()
{
ProgramName.Aa.UpdateListView(someArray);
}
}
But its giving an error because static method can only access static variables,and my listview isnt static(i created that listview in vs designer).
If i remove static keyword from method in partial class then i cant access it.I tried to create instance of partial class but without success.Any idea is welcome
note:Im using Invoke in my UpdateListView method because later that will be running on new thread
The nature of an object-oriented language is that objects don't have universal access to modify other objects. This is a good thing.
You've provided relatively little code so it's hard to provide a perfect answer here, but there are a few paradigms that resolve this issue.
One is to pass the instance to your test class, like this:
class Test
{
test(ProgramName.Aa form)
{
form.UpdateListView(someArray);
}
}
Or, if class test actually contains the ListView, you can pass that to a static method in Aa.
class Test
{
ListView someListView;
test()
{
ProgramName.Aa.UpdateListView(someListView, someArray);
}
}
Ultimately, you should think about the logical relationship between these objects to determine how these objects should communicate.
Remove the static keyword from UpdateListView, as you have done before. In test(), you need to instantiate Aa before you access UpdateListView.
Aa temp = new Aa()
You can then access the method by using
temp.UpdateListView(someArray);
Hallo I would like to create an extension method for Char class that works as Char.IsDigit() method (but that will of course recognize a differnt type of characters).
I wrote this:
namespace CharExtensions
{
public static class CompilerCharExtension
{
public static Boolean IsAddOp(this Char c)
{
return c.Equals('+') || c.Equals('-');
}
}
}
that works fine but that it's not exactly what I meant.
This extension should be used this way:
using CharExtensions;
char x:
...
if(x.IsAddOp())
Console.WriteLine("Add op found");
While I would something like this:
using CharExtensions;
char x;
...
if(Char.IsAddOp(x))
Console.WriteLine("Add op found");
Thanks to everyone who could help me.
You cannot do that, as extension methods will always require an instance of the object.
See here
Extension methods are defined as static methods but are called by using instance method syntax.
Your question mention to fire a static method of a class. You actually want to define a static method for Char class, not add a extension to char instance. to define a static method you must access the original class something like
class SomeClass {
public int InstanceMethod() { return 1; }
public static int StaticMethod() { return 42; }
}
Now you can use StaticMethod as:
SomeClass.StaticMethod();
Then you must access to Microsoft .net framework code to add IsAddOp(x) method to Char class. Actually your way to define a extension with that one you say in question is wrong.. you dont try to define Extension method..you try to define Static method.
I have a button click event in class1test where I want to set the value of d_testNumber to 3. Then in class 2test I want to be able to do an if test and if d_testNumber show a message box. My problem is that d_testNumber is always 0 in class 2test. Can someone tell me how to get the value from class 1test d_testNumber to class 2test?
This is in class 1test:
public int d_testNumber = 0;
Method in class 1test :
void miEditCopay_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
d_testNumber = 3;
}
This is in class 2test:
public int d_testNumber;
Method in class 2test:
public void HelloMessage();
if (d_testNumber == 3)
{
messagebox.show('test worked');
}
If it's a public instance property on the class, like this:
public Class Alpha
{
public int DTestNumber ;
}
Then the other class needs a reference to the appropriate instance of the other class in order to examine it. How that reference is obtained is up to you and the design of your program. Here's an example:
public class Bravo
{
public void SomeMethod()
{
Alpha instance = GetAnInstanceOfAlpha() ; // might be passed as a parameter
if ( instance.DTestNumber == 3 )
{
messagebox.Show('test worked') ;
}
return ;
}
If it's a public static property on the class, like this:
public Class Alpha
{
public static int DTestNumber ;
}
Then in the other class you can do something like this:
public class Bravo
{
public void SomeMethod()
{
if ( Alpha.DTestNumber == 3 )
{
messagebox.Show('test worked') ;
}
return ;
}
Note that static members are singletons with respect to the application domain and the class (Note: statics are per-class properties, not per-intance). Further, if your application is multi-threaded (like a windows program almost certainly is), any changes made to static members are a guaranteed race condition unless you take pains to serialize access via the many synchronization primitives available to you (e.g., the lock statement).
Head First Labs produces some excellent books for self-learning. If you're new to programming, cruise over to Head First Labs and get their Head First Programming: A learner's guide to programming using the Python language (and yes, it does use Python, but for most languages, the skill of programming is not related to the language used.
If you already know something about programming, but are new to C#, then get get a copy of, Head First C#: A Learner's Guide to Real-World Programming with C#, XAML, and .NET. Highly recommended.
if you want to use the same value as defined in class 1 then you have 3 options
Make the variable static in first
if you don't want to make it static you need to pass the value to the other class
Example of 1:
public static int d_testNumber = 0;
if (Class1test.d_testNumber == 3)
{
//your code
}
Use static in declaration.
public static int d_testNumber = 0;
You would have to specify further. You have a d_testnumber field in both classes, and the 2test class will use the variable of its own.
If you have an 2test object called 2testObject somewhere, you can do:
void miEditCopay_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
2testObject.d_testNumber = 3;
}
And pass 2testObject to the HelloMessage() method
Maybe you want d_testNumber to be static so both classes can easily access it?
in 1test:
public static int d_testNumber;
//rest of code the same
in 2test:
if (1test.d_testNumber == 3)
{
//code
}
(Assuming both classes are in the same project / namespace, if not you may need a reference / using statement at the top)
I'm trying to make a program in Visual C# that has my one created class, and at application launch it creates an array of my class object, and this array of my object can be used all over the program. So any function, or a control's event can access the array of objects and their member variables.
I created my class as "public" but for some reason i get these errors upon build:
"The name 'MyArrayObjectNameHere' does not exist in the current context"
When I try to access the objects member variables inside a load file dialog event in which I am trying to load data from a file into the member variables of the object array.
Is there a certain place the object array needs to be declared and constructed so it exists in every context? If so, can you tell me where this is?
I currently declare it in the main function before form1 is run.
My class definition looks like this in its own .cs file and the programs namespace:
public class MyClass
{
public int MyInt1;
public int MyInt2;
}
I declare the array of objects like this inside the main function before the form load:
MyClass[] MyArrayObject;
MyArrayObject = new MyClass[50];
for (int i = 0; i < 50; i++)
{
MyArrayObject[i] = new MyClass();
}
Thanks in advance for any help.
Your problem is that you are defining it within the main function, hence it will only exist inside the main function. you need to define it inside the class, not inside the function
public partial class Form1:Form
{
MyClass[] MyArrayObject; // declare it here and it will be available everywhere
public Form1()
{
//instantiate it here
MyArrayObject = new MyClass[50];
for (int i = 0; i
Only static objects are available in all contexts. While your design lacks... er, just lacks in general, the way you could do this is to add a second, static class that maintains the array of your MyClass:
public static class MyClassManager
{
private MyClass[] _myclasses;
public MyClass[] MyClassArray
{
get
{
if(_myclasses == null)
{
_myClasses = new MyClass[50];
for(int i = 0; i < 50;i++)
_myClasses[i] = new MyClass();
}
return _myclasses;
}
}
}
Do yourself a fav and grab CLR Via C# by Jeffrey Richter. Skip the first couple chapters and read the rest.
You need to make the array a static member of some class, .NET does not have a global scope outside of any class.
e.g.
class A
{
public static B[] MyArray;
};
You can then access it anywhere as A.MyArray
That't good.It is very useful for learners like me.