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.
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 3 years ago.
Improve this question
In C# 8.0 we can now use using declarations in C# 8.0. Are they really such a good idea? Consider this using statement:
private int SomeMethod()
{
using (var t = new StreamWriter("somefile.txt"))
{
} // dispose of variable t
// 100 lines of code
}
As soon as the closing brace is reached, the variable t is disposed of. With using declarations, the scenario is different:
private int SomeMethod()
{
using var t = new StreamWriter("somefile.txt");
// 100 lines of code
} // dispose of variable t
The variable t is only disposed at the end of the method. Using statements seem more efficient to me, because you only keep the object "alive" for as long as you need it.
The answers can be as many as different scenarios.
In your case for example it could either be:
The function is big enough that it do would make sense to split. Remember that in modern programming with unit testing in mind, the units must be sufficiently small and the functions to do specific things.
The 100 lines will end in quite quickly. If that's the case, then it's ok to use the new more readable definition.
The same resources are needed a few lines below. Then why not use the same instance and then dispose?
In the rest of the lines, something else happens that takes time. Then it does not make sense to keep an item non-disposed (like a Stream) and the old way should be used.
The list could go on. There is no one solution fits all example but in most cases I think the first applies.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm currently doing work which requires me to convert VB.Net code to C#.
I've been using the "Builder Pattern" primarily and this has me converting many functions that are one single call of a function ie. SomeFunction(var1,var2,var3) into:
Dim Director As New SomeDirector
With Director
.SomeProperty = SomeValue
.SomeProperty2 = SomeValue2
End With
My concern is that this creates 5-6 lines of code rather than one single line. Is there a way for me to do this in a more concise way or is it better to have the 5-6 lines of code?
Thanks!
As already mentioned, you can do something similar in C# with object initialisation:
var Director = new SomeDirector { SomeProperty = SomeValue, SomeProperty2 = SomeValue2 };
This does not require you to write an explicit constructor.
One neat way to write that is with a constructor in the SomeDirector class:
public SomeDirector(int value1, int value2)
{
this.SomeProperty = value1;
this.SomeProperty2 = value2;
}
then your code sample becomes:
var director = new SomeDirector(someValue, someValue2);
The idea here is that while the constructor looks a bit long-winded, it's tucked away in the class and the code that calls it is nice and concise (and you can't forget an important property).
In case you wondered, there's no C# equivalent of VB's with keyword.
More of a general answer to your question:
In theory it doesnt matter how many lines of code you have, only how much resources it costs to execute. But best practices are also about human readability so it really depends on the situation. Do you need to optimize for performance or further development. This is something that in most cases you as a developer will know better than anyone else who dont have the full insight.
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 :-))
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 asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on a memory reader/writer class, but i am stuck with it.
My problem is that i want to modify an other process memory values with a struct pointer.
I know how to do it in C++ but not with C#
My current code is:
class CModifier
{
struct Data
{
int iMember;
float fMember;
}
public CModifier()
{
Data data[62];
*data = 0x123456;
// use them to modify values etc.
data.fMember = 1.2345f;
}
}
C# does allow limited access to memory locations, but it is not really recommended, and should only be attempted once you know how other systems such as garbage collection handle your memory. The reference operator & and the de-reference operator * are used for accessing memory. you also must use the unsafe keyword in your method declaration. as an example:
public unsafe void Method()
{
int x = 10;
int y = 20;
int *ptr1 = &x;
int *ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
Note that there are other more advanced things to consider, such as Pinning memory locations to stop the garbage collector from moving the object in memory, and the effect this process would have on your stack heap.
Bottom line, Use pointer references at your own risk, and only as a last resort.
I feel like C++ professionals are going to lambast my post for not using correct technical terms, but oh well.
C# has an 'unsafe' modifier you can use to have pointer-adjusting code, but a better option for modifying structs in another location is the 'ref' keyword.
I can't say -exactly- what you're trying to accomplish can be done in C# (heck, I'm not sure I'd understand it in C++), but here's how I'd do it, as you've described.
void ChangeMyStruct(ref Data etc) {
data.fMember = 1.2345f;
}
void mainMethod() {
ChangeMyStruct(ref dataOne);
}