Data persistance in class library between one class methods - c#

I am creating a class library for AutoCAD with .NET.
The problem is that the methods are called one after another from AutoCAD and first one reads input file and creates List of data in memory. However when the new one is called the list is empty.
I need to find a solution how to keep that data.
The List contains data in my created structure. Methods are called independently, but in order.
Short code example:
namespace GeoPjuvis
{
...
public class Program
{
...
//program variables
private List<GeoData> dataList;
private List<DataPoint> points;
private int mapScale;
public Program()
{
dataList = new List<GeoData>();
points = new List<DataPoint>();
}
//Initialization method of the program. Makes praperations. Reads files. Add points to map.
[CommandMethod("geoinit", CommandFlags.Session)]
public void Init()
{
...
}
//method uses data gathered before and selects points
[CommandMethod("selectPoints", CommandFlags.Session)]
public void SelectPoints()
{
...
}...
So why these dataList and points lists are empty when I call SelectPoints() method. And how to avoid that?

I don't know about programming for AutoCAD, but I'd suspect that it's creating a new instance each time. You could try making the variables static (e.g. class-level):
private static List<GeoData> dataList = new List<GeoData>();

Is it instantiating a new class each time it calls a method? (Forgive me, I'm not familiar with coding for AutoCAD.) Try making the class static. If that doesn't work, can you return the value(s) from the first method to AutoCAD and have it send those as arguments to the next method? That wouldn't be the best solution for performance, keep in mind.
Also, for reference, take a look at the a Singleton implementation in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx

At a guess, based on the information you've given, does AutoCAD create a new instance of your object for each method call? This would explain why your instance variables are empty.
Try making the variables static and see if the data persists across method calls.
Does the AutoCAD docs have any instructions for writing these programs?

It looks like you are calling a new instance of your class, You could implement a singleton pattern to make sure you are always calling the same instance or persist the points and load them second time round.
Here's a good link for the Singleton implementation in c#, http://csharpindepth.com/Articles/General/Singleton.aspx

Related

C# in Unity 3D/2D: Am I required to use Classes for every script?

A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].

how to create a static list of objects within their constructor in c#?

I want to maintain a list of all instances of my class that are created. I thought I could do that by adding 'this' to a static list from within the constructor. Of course C# doesn't let me reference 'this' in the constructor because it's not fully constructed yet. That makes sense but I'm trying to figure out the best way to accomplish this.
class Thing
{ static List<Thing> AllTheThings;
public Thing()
{
AllTheThings.Add(this); // can't reference 'this' here
}
}
I can think of two ways to this:
Make the constructors private and create a static method ('MakeNewThing') that invokes the constructor and adds the new instance to the list. I worry about potential problems with not having a public constructor but I'm not sure what they are.
Create a shell class ('ThingShell') that contains Thing's. The constructor for ThingShell creates a Thing and adds it to the list. This is messy and requires ThingShell to proxy all of Thing's members.
I seem to remember doing something like this in C++ about 20 years ago but don't recall the details and can't find the code.
Anyone have a better ideas?
As #Jon Skeet said, that reference to "this" should have been fine. But just in case, here is an alternate method.
public class Thing
{
public readonly static List<Thing> AllTheThings = new List<Thing>();
//making the constructor private so that no other code can call it.
private Thing() { }
//providing a static instance method for creating the object
public static Thing Instance()
{
var t = new Thing();
Thing.AllTheThings.Add(t);
return t;
}
}
Now, the thing (excuse the pun) to watch out for in this implementation is that, by having this static list of all "Things" instantiated by the app, you will run the risk of a memory sinkhole if you do not have a way to get rid of old "Things" when they are no longer needed within scope.

referencing other class methods without creating a new instance

I have a class by itself called clientChat that does basic network stuff. I have several other classes linked to different window forms. In my first form I have a variable referenced to the chat class like so:
clientChat cc = new clientChat();
Everything works okay their, the class has been initialized and everything is in motion. After the first forms is done performing it's duty I bring up my second form that's obviously linked to a new class file.
Now my question is, how can I reference what's going on in the clientChat class without setting a new instance of the class? I need to pass data from the form to the networkstream and if I create a new instance of the class wouldn't that require a new connection to the server and basically require everything to start over since it's "new"? I'm a bit confused and any help would be great, thanks. C# on .NET4.0
You could create an instance of clientChat in the beginning of your program and then, simply pass its reference to the classes that need it.
You may want to look into the Singleton design pattern. Mr Skeet has written a good article on how to implement it in C# here. (Just use version 4. its the easiest and works fine =) )
Presumably you would either:
Create the object from the code that creates and shows both forms, and pass a reference to that same instance to both forms, or:
If you create the second form from inside the first form, pass a reference to the instance referenced by the first form to the second somehow (via a property or a constructor, for example).
In additional to #Jens's answer, there are 5 approaches on the linked page, while I think we have the 6th using Lazy<T> in C# 4.0
public sealed class Singleton
{
private Singleton() { }
private static readonly Lazy<Singleton> m_instance = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return m_instance.Value;
}
}
}

C# Beginner, writing/calling a Method

When we write a method, say an easy one like
void myMethod()
{
// code here
//
}
and we call it from within Main(), it's done essentially this way:
Program myProgram = new Program ();
myProgram.myMethod();
Obviously, myProgram is entirely arbitrary (taking into consideration, of course, coding conventions) but what's up with the reference to Program?
You are declaring your method myMethod inside a class called Program. Since your method is not a static method (i.e. it is not static void myMethod()) it requires an instance of Program in order to work. Therefore you need to create a new instance of Program in order to invoke myProgram.myMethod() on it. If myMethod were static, you could have called it simply by Program.myMethod() or, since you're already inside that class to begin with, myMethod() (since the current class name is implied for static methods).
Program is a class, which contains methods. By default the only method it contains is static void Main(...).
If you add your non-static method myMethod it doesn't belong to the class Program, but rather to instances of Program (called objects).
Static methods (like Main) can be called directly from the class:
Program.Main(...);
Non-static methods must be called from objects of the class:
Program program = new Program();
program.myMethod();
Classes are designed to group together like functionality. Program isn't a good place to put these. You should create other classes, and use them throughout your code.
By using classes you keep like code together, and provide a mechanism to reuse the same code over again from different places. You can create as many different instances of 'Program' as you like, from many different classes, and invoke the 'myMethod' method on each of them.
For instance you might have a ClassRoster and a Student class, which can be used like this in the ClassScheduler class:
ClassRoster roster = new ClassRoster();
Student studentOne = new Student();
studentOne.StudentId = "123456";
roster.EnrollStudent(studentOne);
Program is the type, that defines myMethod in your question. In C# methods are defined by types.
You can either call methods via an instance of the defining type or via the type itself (if the method is static). Since myMethod isn't static, you need an instance of the type Program to call it.
use this:
public void myMethod()
{
// code here
}
in main method:
Program myProgram = new Program();
myProgram.myMethod();
Thanks everyone.
I went back to my code; I added static in front of myMethod, and in doing so the Program myMethod = new Program() became unnecessary (uncompilable? illegal?), and it can be called simply by writing myMethod() Obviously I need to study up on what static does and how it affects methods/classes!
I'm actually only in week #3 of my .NET class... our instructor, while very smart, leaves something to be desired in the teacher category. The assigned text for the class is only so-so in my opinion, at least for me and how I learn (Programming C#, O'Reilly) This is a very good community, thanks!

Cross class communication without refering the instances C#

I have two classes that are instantiaded and loaded at runtime. I would like to check the resources of one without having to refer the instances as it can get messy if there are a lot of checks and classes.
For example, if I have the two following classes and I want to call one from another.
Class Item
{
private int id;
private int loc;
void Item()
{
// the Class actually has some properties with get set, but thats not the point here.
id = 1;
loc = 2;
}
public bool check()
{
// Check if the several fields are ok for DB submission
// how Can I refer to the other class from here? Do I have to pass the instance as a parameter?
return Locals.Exists(loc); // does not work because its not static!
}
}
Class Locals
{
Hashtable l = new Hastable();
void Locals()
{
// This will actually be loaded from a DB at runtime.
l.add(1, "Local 1");
l.add(2, "Local 2");
}
public bool Exists(int i)
{
return l.ContainsKey(i);
}
}
//Form Code:
main()
{
Item newItem = new Item();
Locals allLocals = new Locals();
newItem.check();
}
Is there a way to do this without having to call
newItem.check(allLocals);
From what I saw, even with delegates, the caller classe need the instance of the other class.
In short, Is there another way to promote cross Instances communication?
Was I confusing enough?
not sure i understand what you mean, but i usually add for similiar cases a static list with all of the objects
Class Locals
{
public static List<Locals> MyLocals = new List<Locals>(); // first thing i add
Hashtable l = new Hastable();
void Locals()
{
// This will actually be loaded from a DB at runtime.
l.add(1, "Local 1");
l.add(2, "Local 2");
MyLocals.Add(this); // second thing i add
}
and then you can get the objects from a static context.
be sure to edit the dispose function as well, otherwise the GC will not work.
It's not entirely clear what you're trying to accomplish here, but one option to fix the problem of passing lots of instances around is to use an IoC framework (Ninject is one example, but there are several available to choose from.) Because instances are injected dynamically as your objects are constructed, this can help to reduce inconvenient glue code. There are other patterns available to allow the classes to find eachother (a Singleton instance or some form of Repository that allows lookup of an instance using some identifying data.) It's also possible to use a Message passing design, which strongly decouples the classes, at the cost of some additional overhead.
It really depends on what you're trying to do. Every design will have its pros and cons.
How can I refer to the other class
from here? Do I have to pass the
instance as a parameter?
Yes, the only way to communicate with an instance is to get a reference to it (or an intermediary). Since Locals isn't a static class, pass an instance to an Item constructor or method parameter.

Categories