How can I access a class array from another class - c#

public partial class FormRestaurant : Form
public Tables[] AllTables = new Tables[4];
I create an array of type Tables which is a class that I made. If I try to reference this from a third class (Parties.cs) by doing:
public void AssignTable()
{
for (int i = 0; i < **FormRestaurant.AllTables**.Length; i++)
{
if (**FormRestaurant.AllTables[i]**.TableCapacity <= PartySize)
{
}
}
}
I am told that I need an object reference. How exactly do I do this?
I tried making the array static but it didn't seem to work. Also I get this error when I try to make the AllTables array public.
Error 1 Inconsistent accessibility: field type
'Restaurant_Spil.Tables[]' is less accessible than field
'Restaurant_Spil.FormRestaurant.AllTables'

When it says you need an object reference, it's trying to tell you that it needs an instance of your class. Say you have your class:
public partial class FormRestaurant : Form
{
public Tables[] AllTables = new Tables[4];
}
If you want to get the length of the Tables[] array in Parties.cs, then Parties needs an instance of FormRestaurant; it makes no sense to ask for the length of FormRestaurant.AllTables. Instead you should:
public class Parties
{
int length;
FormRestaurant f;
public Parties()
{
f = new FormRestaurant();
length = f.AllTables.Length;
}
}
the f variable is the object reference that was mentioned in your first error.

All you need to do is put your Tables class public.
You cannot expose private field type in a public class

Related

Access Parent/Owning class variable from composed class?

Forgive me because I know my wording is terrible. I'll just give an example.
public class MainClass{
public int someVariable;
public List<HasAClass> cList = new List<HasAClass>();
addHasAClass(HasAClass c){
cList.Add(c);
}
}
public class HasAClass{
public HasAClass(){
//Modify someVariable in some way????
}
}
public class HasASubClass : HasAClass{
public ComposedClass(){
//Modify someVariable in some way???
}
}
I having trouble finding the right words for this questions but here is what I am trying to do:
I am creating an aid for an RPG similar to dungeons and dragons. Each character can have a variety of special abilitys which can effect the characters in some way (both negative and positive). I am trying do this with a variety of subclasses which store the pertinent info and get added to the character at varying points in time. What I can't figure out is how to modify the properties of the Character(I called it Main Class in my example) when instances of the HasA class are added to it.
The HasAClass needs a reference to the owning instance, so that it can ask the parent for values and update them when required...
public class HasAClass
{
private MainClass _mainClass;
public HasAClass(MainClass mainClass)
{
_mainClass = mainClass;
_mainClass.someVaraible = 42;
}
}
You then need to pass the owner reference into the constructor of the HasAClass when they are created. If this is not possible at the time of creating the instance then you would instead need to assign it as a property after it has been created. Such as inside the addHasAClass method.

Public variable inside a class

I am a bit confused about how public variables work inside a class.
I know that public variables can be accessed without calling the class, whereas private ones cannot.
If you have multiple instances of the same class and in each you give a different value to a public variable then i assume each class instance would have its own unique version of the variable each with a different value.
My confusion is this
What happens if you change the value of the public variable without calling a new instance of the class?
Would all future new instances of the class start with that variable set to whatever you set it to without first calling the class? if not then what happens?
I think you somehow mixed up public variables and static variables. The below statement:
public variables can be accessed without calling the class
Is utterly and plainly wrong for non static variables, might they be private or public.
If you change public variable of a class instance, it will change only that instance, having no effect whatsoever on other existing instances or future instances.
Static variables on the other hand can indeed be called without an instance of the class and changing them has "global" effect, not related to class instance.
(If you have any specific code you worked with and need further guidance please post it)
In languages like C#, you canĀ“t do that.
Accessing any (non-static) variable of a class itself instead of a instance of it
would result in a compiler error.
Perhaps some sample code will help; private variables cannot be accessed so I'm guessing your terminology is getting mixed up. In the below sample, the PublicStaticInt property is declared as static; simply put, that means there is only one copy of it in your AppDomain. Every instance of ExampleClass that is created references that same copy of it. The PublicInt property is an instance property; that means that every instance of ExampleClass has its own copy of that piece of data.
public class ExampleClass
{
public static int PublicStaticInt { get; set; }
public int PublicInt { get; set; }
}
private static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
var example = new ExampleClass();
Console.WriteLine("PublicStaticInt = " + ExampleClass.PublicStaticInt.ToString() + ", PublicInt = " + example.PublicInt);
ExampleClass.PublicStaticInt++;
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
When you create a new instance of same class then every instance has its own values for each data members. for example
class A
{
public int a;
public int b;
public A()
{
a=0;
b=0;
}
}
when i create instance of class A like this
A a11 =new A();
A b11 = new A();
Now if I change the value of a11 it will never change the value of b11 and if I change the value of b11 it will never change the value of a11.
Would all future new instances of the class start with that variable set to whatever you set it to without first calling the class? if not then what happens?
No they will set to values that you have set in the constructor of the class. In this case it will set values of a and b equal to zero for every instance of class because it is done the constructor.

C# Cross-Class object

I'm working on very simple Roguelike game (just for myself) and get a question:
As it is not possible to create a cross-class struct-object (entity in the game case) that could be accessible from any class of my program, what to use to create a cross-class object? I was thinking of something like storing all newly created object (enities) in a static object array, but I guess there is more simple solution on this problem.
Question itself: How to create a cross-class accessible object(s) with your own properties?
Thanks everybody, I found what I was searching for.
It seems like you tried passing around a value type (a struct) between different classes and you noticed that when you update the value in one place it doesn't change the value in another place.
That's the basic difference between value types and reference types.
If you are creating the struct yourself you may want to instead define it as a class.
If not, you could wrap all your structs in a class and pass the class around as your state object.
If all you have is simply a list of the same type of struct (like Points), just pass the List itself around. C# collections are implemented as classes.
public class GameState
{
public Point PlayerLocation { get; set; }
public List<Point> BulletPoints { get; set; }
public double Health { get; set; }
}
Now you can create a GameState and pass it around to different classes:
public class Game
{
private GameState _state = new GameState();
private BulletUpdater _bulletUpdater = new BulletUpdater();
public void Update()
{
_bulletUpdater.UpdatePoints(_state);
// Points have now been modified by another class, even though a Point is a struct.
}
}
public class BulletUpdater
{
public void UpdatePoints(GameState state)
{
for (int i = 0; i < state.BulletPoints.Count; i++)
{
Point p = state.BulletPoints[i];
state.BulletPoints[i] = new Point(p.X + 1, p.Y + 1);
}
}
}
Just remember in the above code if I were to write:
Point p = state.BulletPoints[i];
p.X += 1;
p.Y += 1;
That wouldn't affect the original point! When you read a value type from a list or from a class into only copies the value into a local variable. So in order to reflect your changes in the original object stored inside the reference type you need to overwrite it like so:
state.BulletPoints[i] = p;
This same principal is why the following also will not work:
state.PlayerLocation.X += 5; // Doesn't do anything
state.PlayerLocation.Y += 5; // Also doesn't do anything
The compiler would tell you in this case that you are doing something wrong. You are only modifying the returned value of the property, not the backing field itself. You have to write it like so:
state.PlayerLocation = new Point(state.PlayerLocation.X + 5, state.PlayerLocation.Y + 5); // This works!
You can do the following:
Using IoC Framework, like Ninject. You can setup Ninject to create single instance for all usages.
The other option is to use Singleton pattern design pattern
And the third one is to use static property
It sounds like you want to use the Singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example of what this would look like in C#:
public class Singleton
{
static Singleton()
{
Instance = new Singleton();
}
public static Singleton Instance { get; private set; }
}
It's possible. What about public and static class?
public static class CrossClassObject
{
public static object MyProperty { get; set; }
public static void MyMethod() {}
}
Of course this class should be placed in the same namespace that other ones.
How to use it?
class OtherClassInTheSameNamespace
{
private void SomeMethod()
{
var localVariable = CrossClassObject.MyProperty; // get 'cross-class' property MyProperty
CrossClassObject.MyMethod(); // execute 'cross-class' method MyMethod()
}
}
No idea what you are trying to achieve... but if you want a list of objects accessible 'cross-class', just make a static class with a list of objects and then when you reference your class from any other class, you will have access to its list of objects. Here is something like that:
public static class ObjectController
{
private static IList<object> existingObjects;
public static IList<object> ExistingObjects
{
get
{
if (existingObjects == null)
{
existingObjects = new List<object>();
}
}
}
}
public class MyObject
{
public MyObject()
{
ObjectController.ExistingObjects.Add(this);
}
public void Delete()
{
ObjectController.ExistingObjects.Remove(this);
}
}
Then you can add stuff like
MyObject newObj = new MyObject();
//// other stuff... This object should now be visible to whatever other class references ObjectController
newObj.Delete();

custom class library as an array C#

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.

In Visual C# I cannot make my public class public

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.

Categories