Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
In my program, I have to add new instance of a given class to an ArrayList each time a method is invoked. My code looks like.
public class A
{
List<Object> myList = new List<Object>();
void resetMyList()
{
myList.Clear();
myList.Add(new B());
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
public class B
{
public override string toString()
{
return "I'm B";
}
}
One of my colleague suggested to add new property to class A that refers to one instance of class B. So class B will only be created once and stay in the memory. With this solution, we can avoid to make the garbage collector works on creating and deleting new instance of B. Here is his code:
public class A
{
List<Object> myList = new List<Object>();
private B b = new B();
void resetMyList()
{
myList.Clear();
myList.Add(b);
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
So which suggestion is better, design and performance wise?
Edit: Please I know that using:
Using List is better than using ArrayList
Codes are not equivalent
I just want to keep the example simple and my concern is about design and memory. Whether to add private member and keep it in memory or create new instance each time and avoid extra members.
Any way I will change the code to use List
Well, First of all - these codes are not equivalent - While in the first code you create a new instance of B every time you clear the ArrayList, in the second one you use the same instance of B all the time. This means that any changes made to this instace (assuming that B is not immutable) will be "canceled" every time you clear the ArrayList in the first code, but persist in the second one.
As to the question of which one is better "performance wise" - It usually depends on so many factors that it's almost always impossible to answer with complete confidence. In fact, it's so hard to answer this question correctly that Eric Lippert wrote an entire blog post about it - and if it's hard for someone like him to answer - it's hard for anyone (unless your name is Jon Skeet :-))
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Imagine I have the following class:
public class MyWeirdCollection
{
private IList<string> _myTrueList;
private IList<string> _myFalseList;
public MyCollection()
{
_myTrueList = new List<string>();
_myFalseList = new List<string>();
}
public void Add(string item, bool listType)
{
if (listType)
{
_myTrueList.Add(item);
}
else
{
_myFalseList.Add(item);
}
}
public IList<string> Get(bool listType)
{
return listType ? _myTrueList : myFalseList;
}
}
How would I go about unit testing the Get and Add methods? I'm doubting between 2 possible solutions:
Making the 2 lists protected instead of private, so I can create an inheriting TestableWeirdCollectionClass that exposes the content of the lists to the test
Leave the class as it is and test Add and Get together? i.e. calling Add to add some elements and then Get to see if the correct values come back.
I'm leaning towards option no. 2, but would like some more opinions. Thanks.
Definitely go for the option 2. Pretty much every test I can imagine must go though Add, then Get, together.
When testing you are ultimately testing the public interface, not the internal state. The whole idea of the test code is that you give items to it, then you get them back with the appropriate key. In your particular case it uses private lists to hold the items, but this may not be the case (you might store them to a database or file, rely on another class or something else). This is ultimately an implementation detail, the important bit is that Add and Get always play together, therefore you should it.
I would strongly recommend option 2. The reason is that your whole class should be consider a unit, and be tested as such. Making methods public for the sole purpose of unit testing can be motivated in some rare cases for very complex classes, but should be avoided if at all possible.
See also
Is it bad practice to make methods public solely for the sake of unit testing.
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a class with functions to read data files. When read the class stores this datas in public properties.
After that I write the content of the puplic properties into a database.
Then it repeates. This means I read again datas with this class.
Before it repeates I want to clean the class.
What is the best way to do it?
Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?
Let's assume your class looks similar to:
public class MyClass
{
public double IntField { get; set; }
public string StringField { get; set; }
}
And your application something like:
public class MyApp
{
public void Execute() {
var myClass = new MyClass();
// set properties
myClass.IntField = 123;
myClass.StringField = "Hello";
// save to DB
}
}
Each time your application runs, it will run the Execute method which will create a new instance of your class. This way all class properties will be empty or "clean" as you call it.
create new method , name it let say "clear_data" , call it before load data from function that do it . also may be you will need call it from destructor to prevent memory leaks (in case you have pointers that point to some allocated memory ).
What about Memento pattern? Might be useful for you:
https://www.codeproject.com/Articles/186184/Memento-Design-Pattern
Or, as already pointed out, you have 3 other good possibilities:
- Create a method Clear() that sets properties to default value,
- If you have some unmanaged resources, you can use IDisposable interface,
- Create static readonly property holding Empty instance of the class and reassign it. But I would go with Memento/Clear way.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In the case of the singleton class seen below, what is the proper way to initialize MyList? Do I refer directly to the field MyList (Option 1) or to Instance.MyList (Option 2)? What's best practice here? My gut says go through Instance, but I'm second-guessing myself and cannot find a definitive answer anywhere.
public class Foo
{
private readonly static Lazy<Foo> _instance =
new Lazy<Foo>(() => new Foo());
private List<string> MyList;
public static Foo Instance
{
get { return _instance.Value; }
}
private Foo()
{
MyList = new List<string> {"a","b","c"}; //Option 1
Instance.MyList = new List<string> {"a","b","c"}; //Option 2
}
}
To start with, I would say that either way is fine. That being said, I prefer the option that doesn't use the "Instance" identifier. The concept of the instance really belongs to the code outside of the singleton class. Inside the class, the fact that it is a singleton should be well known. Thus, specifying the Instance identifier is redundant.
The Singleton pattern is for creating types that can only have one instance, but are still treated like instances of a type, rather than being treated as just a type like static types. So if MyList is part of the single instance, then it should be an instance variable on that instance, not a static member of the class.
One of the perks of the Singleton pattern is that it is easier mock for testing and also easier to transition to using multiple instances later, compared to using static members and classes. For these purposes, making MyList an instance member also helps.
If using an instance, you can write MyList or this.MyList within that instance or Instance.MyList from other places. None of these are more correct than any others, it really depends on what you find readable. The important thing is to not mix conventions, which is the worst readability option.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to coding and still at college at the moment. Sorry if this question has been asked before but I could not see it any where.
I was wonder if it is possible to create a constructor for the array Class, so each time I create a new array I can execute code such as count the amount of arrays I have in my application for each instance I make? I understand the Array class is abstract so you cannot make an instance of it.
Are int[] arrays just methods within the abstract Array class?
Any insight as to why it is or isn't possible would be greatly appreciated!
Thanks
If your custom code is just to populate the array, C# provides several built in ways to do this (see All possible C# array initialization syntaxes).
If you want to have code execute every time you create an instance of a particular kind of object, you should make a class that represents that object (you might be able to do an extension method as well, but that would likely get confusing over time). This class might be nothing more than a wrapper around an array:
public class MyArray<T>
{
private T[] _array;
public MyArray()
{
// execute your always must run code here!
}
public ArrVal
{
get { return _array; }
set { _array = value; }
}
}
...
MyArray<int> myArray = new MyArray<int>(); // your custom code gets executed when you new up the object here
However, per best practices, you should avoid having code in a constructor that does too much work (and in my experience, having a constructor that throws exceptions can cause some problems that are hard to debug, although MSDN says it's better to throw the exception than to cover it up). If this code is going to be doing intensive work, it may be better to create a separate method (maybe something called public void Initialize()) so that callers can new up the object more lazily.
You should also avoid trying to have this done for all arrays, because I can guarantee it'll cause problems for you or someone else down the road when they can't figure out why int[] arr = new int[3] is doing extra stuff. You should look to properly use encapsulation here instead (i.e. creating a wrapper/extension/decorator class).
Also, it's entirely possible that one of the existing .NET classes for Collections fulfills your needs... Look into those.
I'm not sure if I understand your question correctly, but if you want to be able to execute code when you create an array you can use LINQ:
int[] myArray = new int[10]
.Select((x, idx) => /*execute your code here*/).ToArray();
So you can create an array of length 10, then you can execute code for each element to determine what you want to populate it.
For example you could fill the array with random numbers using:
Random random = new Random();
int[] myRandomArray = new int[10]
.Select((x, idx) => random.Next()).ToArray();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm a beginner in C# and am trying to understand the effects of declaring variables in different scopes. Is there any appreciable performance difference between:
Example 1
class A
{
static int i;
static string temp;
}
class B
{
while(true)
{
A.i=10;
A.temp="Hello";
}
}
Example 2
class B
{
int i;
string temp;
while(true)
{
i=10;
temp="Hello";
}
}
Example 3
class A
{
public int i;
public string temp;
}
class B
{
A D = new A();
while(true)
{
D.i=10;
D.temp="Hello";
}
}
The first code snippet shares both variables: they get allocated statically, and all threads would use them in concurrent environments. This is very bad - one should avoid situations like that in production code.
The second and the third code snippets are thread safe. The third snippet groups variables i and temp; the second snippet does not. In addition, the third snippet needs an extra allocation of an object, and creates an object to be collected upon return (of course it never returns because of the infinite while (true) loop, so it does not really matter).
If the two variables do not belong together logically, you should avoid making a class for them. If they do belong together, you should move the code that uses these variables into the class that declares them.
As far as the performance and memory implications go, the third snippet requires an extra chunk of memory compared to the second one, but it is too small to pay attention to. The performance difference will be nearly impossible to detect, so you should not worry about it much: in most cases, it is best to optimize your code for readability.