Initialize int variable to minus one in C# [closed] - c#

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 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2

TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible

Related

multiplication in C# basic program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In the Main function, declare three integer variables (name them arbitrarily) and initialize these variables with values (ideally different). Write a program that computes the following arithmetic expression: Multiply the values of the last two variables and subtract the value of the first variable from the obtained result. Write the arithmetic expression and its result on the screen in a suitable way.
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int prvni = 10;
int druha = 20;
int treti = 30;
int vysledek = (treti * druha) - prvni;
Console.WriteLine("Výsledek: {vysledek}");
}
}
}
String-interpolation in that way requires a $ (dollar-sign) before the string to specify that you are doing interpolation, so: Console.WriteLine($"Výsledek: {vysledek}");
For more examples on string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
An alternative solution could be to simply concatenate the variable to the string: Console.WriteLine("Výsledek: " + vysledek);
You need to print the varable correctly.
Console.WriteLine("the answer {0}", vysledek);
Take care,
Ori

How to use a variable instantiated outside a method in C#? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to know how to use a global variable - which I already instantiated it as a public integer type - in a method later.
Here's my code so far:
public int money = 500000;
//other variables
//...some code in between
public static void UpdateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
{
// \/ Problem here
if (money < cost)
{
//uncheck box
}
else
{
//implement input variables with other external variables
}
}
Remove "static" keyword from your method, static method cannot access instance variables. Static method is something belong to the type itself, while your instance variable is not. another option is to put the "money" as static, but than all your instances going to use the same "money" which is probably not what you aiming for.
public void updateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
{
// v- No more Problem here :)
if (money < cost)
{
//uncheck box
}
else
{
//implement input variables with other external variables
}
}

Parameters in parentheses after a method name: what are they and what do they do? [closed]

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 3 years ago.
Improve this question
Newb to C# and OOP. My journey thus far has been to take code bases that I've inherited from former developers and either address issues, or add enhancements, whilst trying to understand said code bases' structures from front-to-back.
I'm having trouble fully grasping the concept around the parameters which follow the initial declaration of a method. Here's an example of a method I'm working with:
public List<Entity> ParseCsvFile(List<string> entries, string urlFile)
{
entries.RemoveAt(entries.Count - 1);
entries.RemoveAt(0);
List<Entity> entities = new List<Entity>();
foreach (string line in entries)
{
Entity entityManagement = new Entity();
string[] lineParts = line.Split('|');
entityManagement.Identifier = lineParts[0];
entityManagement.ProductId = 1234;
entityManagement.Category = "ABCDE";
entities.Add(entityManagement);
}
return entities;
}
The part after ParseCsvFile in parentheses: (List<string> entries, string urlFile)
Could someone explain what these are and what they do, perhaps with metaphors/analogies/real-world examples?
It might be easier to see their purpose if you look at a simpler function for example:
public int Add(int number1, int number2)
{
return number1 + number 2;
}
Above there is a function that adds two numbers together and returns the result. It is a set of instructions to follow. How can it follow the instructions if it doesn't know what numbers to use.
That's where calling the function comes in.
for example:
var result = Add(2, 5);
In this scenario result = 7.
2 is replacing number1 in the function and 5 is replacing number2.

Is there any benefit on declaring a local constant of string over a local variable C# [closed]

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
Is there any noticeable benefit regarding performance on using a constant over a string. Suppose the following case
public void MethodUsingConstant()
{
const string searchedText = "foo";
//some operations using searchedText string
}
public void MethodNoUsingConstant()
{
string searchedText = "foo";
//some operations using searchedText string
}
There is also the option to take this to a class-struct constant field.
Or, should I avoid to overthink too much these micro optimizations?
If you think about it, it shouldn't really be much different. That is because when the computer sees a variable, it retrieves its memory adress and then the value. I have tried this code and the difference is so tiny (less than 3ms: BTW code ran in ~107 ms) that could be down to millions of other variables:
//Just changed to non const
const string s = "hello";
string full = "";
int k = 0;
for(int i = 0; i < 10000; i++)
{
full += s;
}
In general, const vs non const just comes down to this: will that value always stay the same: set it to const, else just leave it. Here is a great link about .NET optimization.
To sum up, You should only get into these tiny details the moment your code can't be optimized in any other way, and when that is the case, your code is just fine.

Is encapsulate a private field into a variable a good practice? C# [closed]

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
For example:
public class Test
{
private string _s;
public Test()
{
var s = "hello";
_s = s;
}
public void Foo()
{
var s = _s;
// Use s for some reason.
}
}
Should I use _s directly for my needs or store _s into another variable that point to it? What if there were a property instead of the private field?
First, "encapsulate" is not at all the word for what you're doing. You're talking about making a copy. In programming, to "encapsulate" means to hide the field and make everybody access it via code of some kind. In C# that almost always means a property (which is really just method calls disguised by syntactic sugar). In other languages it might be explicit get and set methods.
So. Should you make a copy?
Yes:
private int _from = 9;
public void f(int to)
{
for (int i = _from; i < to; ++i)
{
// stuff
}
}
No:
public f2()
{
Console.WriteLine("from is {0}", _from);
}
If you're going to be changing the value as you use it, but you don't want the private field to be changed, make a local copy and change that.
But beware: Value types such as int behave very, very differently than mutable reference types such as SqlConnection (see below).
If you won't be changing it, don't waste your time. In fact, if the field is a reference type and you create a local reference to it, somebody maintaining your code ages hence may mistake it for a local object and wrongly assume that changes to it won't have class-wide effects.
private SqlConnection _conn = null;
public MyClass()
{
_conn = new SqlConnection();
}
public void f3()
{
var c = _conn;
// 150 lines of stuff
// OK, I guess we're done with it now!
c.Dispose();
c = null;
// Now _conn is not null, yet the next call to f3() will find it unexpectedly
// in an invalid state. You really don't want that.
}
Where did you get this idea from?
I see no reason to proxy the private field with a local variable. Most of the time, that field will be of a reference type (i.e., more or less, a class), so using a local variable only means one more reference to that object.
It could actually be harmful (anyway, doing unintended things) if you did that with a value-type field (an int, for example). You would act on the local variable, which is fine as long as you read it; but on write the field would not be changed.

Categories