C# Use list defined in method in other methods - c#

First of all I'm quite a beginner in working with C# so please be kind :D
I am currently working on a project where I need to get data in the form of various lists from an API and then use it further.
Getting the data is generally not a problem. The whole thing happens in a method 1.
However, I now have to use the contents of these lists in a method 2 and I am absolutely at a loss as to how I can implement the whole thing without carrying out method 1, in which the list is filled, again in method 2.
Maybe someone can help me and tell me how I can use lists that were filled in method 1 in method 2 without calling and executing method 1 in method 2.
Thanks for your help! :)

Store the list in a field, i.e., a variable at class level, outside of a method instead of using a local variable, i.e., a variable declared in a method.
private readonly List<int> _list = new();
private void Method1()
{
_list.Add(2);
_list.Add(3);
_list.Add(5);
_list.Add(7);
}
private void Method2()
{
foreach (int i in _list) {
Console.Writeline(i);
}
}

Related

Instantiated variable does not contain any value

I have a class called ClassModel. This is how it looks.
class ClassModel
{
dynamic ConnListInstance;
public ClassModel() {
ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
}
public void checkCount() { //this shows a count of 0
Console.WriteLine(ConnListInstance.Count());
}
public void checkCountVersionTwo() { //this shows a count of 1
ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
Console.WriteLine(ConnListInstance.Count());
}
}
I have instantiated the class in my main page by declaring ClassModel obj = new ClassModel().
But when I try calling the checkCount method, it returns 0 instead of 1. The checkCountVersionTwo returns 1 but only because I have added the instantiation from the constructor.
Is there something wrong with the way I have created my constructor and class? May I know why it is returning a null/empty value? Shouldn't the variable ConnListInstance have a value upon creating a new ClassModel object?
This has nothing to do with your code, but the reason is in the way how this object works.
Please read the documentation:
An autECLConnList object provides a static snapshot of current
connections. The list is not dynamically updated as connections are
started and stopped. The Refresh method is automatically called upon
construction of the autECLConnList object. If you use the
autECLConnList object right after its construction, your list of
connections is current. However, you should call the Refresh method in
the autECLConnList object before accessing its other methods if some
time has passed since its construction to ensure that you have current
data. Once you have called Refresh you may begin walking through the
collection
(emphasis mine)
So the solution is:
public void checkCount()
{
ConnListInstance.Refresh();
Console.WriteLine(ConnListInstance.Count());
}
Is this the complete code without any other manipulation anywhere?
Ad per this, following seem the case. Please add further code to clarify.
In constructor, you will have a valid instance, unless the CreateInstance fails for some reason
In 1st check method, you will get the count of whatever entity it holds (from construction time to method call time).
In 2nd check method, you are recreating the object and again retrieving its count in same block. So any possible time for entity's to be added to list is within the constructor of ConnListInstance.
Hence, for #2, it seems that you are manipulating the underlying data being contained and hence the list count is reported as 0; whereas at time of fresh construction, it's reported as 1.

Memory consuption: is better a static variable or not?

I'm building a dll that have a Singleton pattern, so essentially the user add my dll, import the reference and execute a method like so:
FooClass.Foo();
now suppose that this method return a list each time, and have this structure:
static class FooClass
{
private static List<string> _fooList = new List<string>();
public static List<string> Foo()
{
_fooList.Clear();
//list population
return _fooList;
}
}
how you can see in the method Foo I clear each time the list instead of creating new instance of that list I reuse the object.
My question at this point is:
Is better create a new istance of the list inside the method Foo, or use the same list object as in my example?
All the result returned will be saved in another object by the user, so I don't need to keep the list in memory.
Any tips would be appreciated! Thanks.
Is better create a new instance of the list inside the method Foo, or use the same list object as in my example?
The two approaches are not equivalent, because clear modifies the instance that may be in use by some other part of your program. This may lead to significant problems, especially in concurrent environments. Given that the result returned will be saved in another object by the user, the problems are virtually guaranteed in your case if you use clear.
I don't need to keep the list in memory.
Then remove the static _fooList, and simply create a new object each time the method is called. Clearing the singleton on every single call defeats the purpose of having a singleton in the first place.

How to reduce this code using anonymous methods or anonymous types?

I have a web service and some methods and I do NOT want to use this code below, which works fine, because I intend to use this in a multi-threaded app where static (I have read) is not thread safe.
So, what I have done now is simply repeat the code that is in the static method 'returnisTrue()' below, in the body of my web service method "myWebMethod", at points //1 of 3, //2 of 3, and //3 of 3. This works fine but results in bloated code. Is there a more compact way, using functional programming or anonymous methods or what have you that I can use?
Note the compiler choked when I tried to create a class inside the method...which would have solved my problem.
As I say the code I have now works fine but it is bloated, as I repeat the 'static' method 'returnisTrue' three times.
Thank you.
EDIT: in response to some questions about making my static method thread safe, which I rather not bother with, but in the interest of getting a solution I include below.
All this code is server side in a web service
// I cannot unfortunately use this static method below--not thread safe
static private bool returnisTrue()
{
bool isTrue = false;
// do a bunch of stuff here
return isTrue;
}
public bool myWebMethod (string XYZ)
{
//public Class myClassReturnisTrue { … } //will not compile
bool isTrueOrNot1 = returnisTrue(); //1 of 3
/// more code here
bool isTrueOrNot2 = returnisTrue(); //2 of 3
///more code here
bool isTrueOrNot3 = returnisTrue(); //3 of 3
return isTrueOrNot1 && isTrueOrNot2 && isTrueOrNot3;
}
// here is the static method 'returnisTrue' it looks something like this:
static private bool returnIsTrue(string A, string B)
{
if (A.Length() < B.Length())
{
return true;
}
else
return false;
}
What are you actually doing within your static method? Are you modifying any global state or are you only working on local variables? There is nothing wrong with using static methods, or even variables, as long as you take proper measures to make sure that your code within is actually thread-safe.
Both static methods and instance methods can potentially be unsafe depending on what you are doing within them. The main question to ask is, are you accessing any data that is accessible between multiple threads within your method? And if so, why not change your method to be thread-safe (through for example locking).
Take a look for example at the .NET framework itself, it contains various static thread-safe methods throughout.
Edit:
Ok, now that we've seen your method - it is indeed thread-safe already. The method is not accessing any shared data and strings are immutable and inherently thread-safe as a result.
you should be able to use static methods if you lock critical sections (you might want to look it up on msdn -> http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx)

Storing 2-dimensional ints as Readonly/const in separate class whilst keeping non-exposed

This is my first question after having used this place as my "go to" for a general opinion on what works/doesn't/why and the such. So let's try this out...
With my limited experience I've been trying to get my head round the better ways of creating fixed data fields that I can refer back to throughout my program - things like end-user-viewable strings that I show repeatedly and other parameters that I'd like to keep constant and safe from change. I've kept my reused data in separate static classes and put my strings in private static readonly arrays that I expose through the use of wrapping in private ILists that have public getters that return the single string I'm after. Hopefully I've not abused terminology so far!
What I've done so far:
namespace MyNamespace
{
public static partial class Tables
{
private static readonly string[] _Messages =
{
"One",
"Two"
};
private static readonly IList<string> MessagesReadOnly = Array.AsReadOnly(_Messages);
public static IList<string> Messages { get { return MessagesReadOnly; } }
}
}
That much I understand but now I've got a 2 dimensional table of data (int) that I need to store in a similarly non-exposed manner that I can access.
This data is going into its own class as now I'm dealing with a separate real-world data type.
Real-world scenario - I've got different fuels with their associated combustion constants that I'll need to access to perform combustion analysis using data that I get from a gas analyser. So I want to keep these arrays/lists separate with all their methods but I can't seem to figure out how to do this.
If I do like I did before and go via the route of array (but 2D this time) then I run into the issue that it seems (according to info on MSDN) that Array.AsReadOnly(myArray) only works for one-dimensional arrays. I'm not savvy enough to know exactly how to write my own to work around this (assuming that's a simple enough task). So then if I go to trying to use jagged arrays, as that seems to be the other viable route I've found, I get stuck trying to figure out how and where to create the initial jagged array (constructor or as class method) and then what about where to initialise the array within that?
If I didn't need to protect the array then I can put it all in the constructor and that might be ok (as far as I can tell so far) but I have to keep it non-exposed. The first way I understood how that programatically fit within a class but trying to use jagged arrays non-exposed has got me all muddled up. All the examples I see on the web seem to create them and initialise within main which is fine (although exposed) but as I'm putting this elsewhere how can I make it available to anything that might need the data whilst not exposing them?
Hopefully you understand why I feel like I'm going in circles, maybe the answer is really simple and I'm missing the obvious but until I see someone else do similar I can't figure it out, and I haven't been able to find anything close enough to give me the clues. If there already exists a similar post on SO please point me in that direction. Like I've said, I've scoured both MSDN, SO and wandered the web in search of breadcrumbs.
Let me know if you need more info about what I've been trying and thanks for reading.
I've just been adding tags to this question and seen that there's an Array tag so I'm off to see if I can narrow things down some more there. Not sure if I should add that tag too, I could add Lists also...?
This data is going into its own class as now I'm dealing with a separate real-world data t
If you're going to be storing this in a custom class, you could just write a custom read-only indexer property for that class.
This would look something like:
private YourType[,] internalArray; // Create and set this up in constructor or elsewhere...
public YourType this[int row, int column]
{
get
{
return internalArray[row,column];
}
{
Couldn't you use a List<List<Yourcustom_class>> for this purpose and define a public readonly property that has only a getter for retrieving data.
You can initialize your jagged array in the static constructor of your static class.
So
public static readonly IList<IList<int>> array;
static Tables() {
// Init array
// Make it read only
List<IList<int>> ar1 = new List<IList<int>>();
for (int i = 0; i < 10; i++)
{
List<int> ar2 = new List<int>();
for (int j = 0; j < 10; j++)
{
ar2.Add(j);
}
ar1.Add(ar2.AsReadOnly());
}
array = ar1.AsReadOnly();
}

C# Private variable list

I suspect this question illustrates my lack of understanding about what's going on behind the scenes in C#, but hey...
While doing a CRM SDK project in C# that involved a number of private variables (which were CRM objects called "lists", but that doesn't really matter), I found I was repeating nearly the same lines of code. I tried shoving the private variables into an array of type "list", and then looping over this array, and setting the variables one by one. Except that, of course, that didn't work, because (I think) what I'm actually working with is a copy of my list of variables.
Anyway, to cut a long story short, is there a way to set a load of private variables in a loop? Am I missing something very obvious, or is what I want to do not actually possible?
Do you actually need the variables to be separate? Can you just use a collection of some form to start with - not as a copy, but to hold the data without any separate variables?
What were you doing with these variables in the repetitive code? You may find that you can get by with a convenience method instead of really looping.
You could try reflection,
Reflection.FieldInfo fields[] = this.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
Normally you would create a Reset() method that ... resets the members of the object.
If you are using an object/class then the values in the array should be referenced, as opposed to using copies of the values.
Do you mean something like this?
private List<T> UpdateValues<T>(T[] values)
{
List<T> list = new List<T>();
foreach(T t in values)
{
list.Add(t);
}
return list;
}
Then you have a list of T's which should be fairly easy to use. If that's not it can you elaborate the problem a little?

Categories

Resources