Definition, declaration, initialization and assignment in C# [closed] - c#

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 7 days ago.
The community reviewed whether to reopen this question 7 days ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Are these definitions correct in C#?
Declaration = memory allocation
Initialization = set initial value
Definition = declaration and initialization
Assignement = set a new value
static void Main()
{
// Declaration = memory allocation
int x;
// Initialization = set initial value
x = 0;
// Definition = declaration and initialization
int y = 0;
// Assignement = set a new value
y = 1;
}

Strictly in terms of C# the above are not exactly correct
// Declaration = memory allocation
int x;
For types with value-semantics the above is true, but for types with reference-semantics it is not, because there is no allocation that happens. The difference is that memory allocation happens with the new keyword with references. With value types, they are stored in the stack, and the stack is pre-allocated to 4Mb size when a .NET process starts.
An example would be
string x;
the above statement only tells the compiler what x is, and nothing happens really in the program when this is compiled.
// Initialization = set initial value
x = 0;
Here again, I would argue the above is just an assignment, and not necessarily an initial value as nothing stops you from writing
x = 1;
x = 2;
There is nothing different between these two assignments, making one of the an initial value and the other not. This is because we don't know if x was assigned a value somewhere else before.
// Definition = declaration and initialization
int y = 0;
I would call it just an initialization as here fore sure a value is assigned fro the first time.
// Assignement = set a new value
y = 1;
As I said before the above is just an assignment.

Related

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

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

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.

Good parsing approach after tokenization [closed]

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
I wrote a program in which I read a string or file and tokenize it.
Example String :
"int w = sad&&s||a|d++ != == < > >= <= -- sadsa++ % int sads = 232.32; if reg string test = \"Hello World\";% % +- + - / * ** false true"
Exmaple Output:
Token[Type:'Identifier',Value:'int',Line:'1',Position:'3']
Token[Type:'Literal',Value:'w',Line:'1',Position:'4']
Token[Type:'Assign',Value:'=',Line:'1',Position:'4']
Token[Type:'Literal',Value:'sad',Line:'1',Position:'8']
Token[Type:'Logical',Value:'&&',Line:'1',Position:'8']
Token[Type:'Literal',Value:'s',Line:'1',Position:'11']
Token[Type:'Logical',Value:'||',Line:'1',Position:'11']
Token[Type:'Literal',Value:'a',Line:'1',Position:'14']
Token[Type:'Unknown',Value:'|d',Line:'1',Position:'14']
Token[Type:'Literal',Value:'d',Line:'1',Position:'16']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'16']
Token[Type:'Relational',Value:'!=',Line:'1',Position:'18']
Token[Type:'Relational',Value:'==',Line:'1',Position:'20']
Token[Type:'Relational',Value:'<',Line:'1',Position:'22']
Token[Type:'Relational',Value:'>',Line:'1',Position:'23']
Token[Type:'Relational',Value:'>=',Line:'1',Position:'24']
Token[Type:'Relational',Value:'<=',Line:'1',Position:'26']
Token[Type:'Arithmetic',Value:'--',Line:'1',Position:'28']
Token[Type:'Literal',Value:'sadsa',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'37']
Token[Type:'Identifier',Value:'int',Line:'1',Position:'41']
Token[Type:'Literal',Value:'sads',Line:'1',Position:'45']
Token[Type:'Assign',Value:'=',Line:'1',Position:'45']
Token[Type:'DoubleValue',Value:'232.32',Line:'1',Position:'51']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'51']
Token[Type:'Identifier',Value:'if',Line:'1',Position:'53']
Token[Type:'Literal',Value:'reg',Line:'1',Position:'56']
Token[Type:'Identifier',Value:'string',Line:'1',Position:'62']
Token[Type:'Literal',Value:'test',Line:'1',Position:'66']
Token[Type:'Assign',Value:'=',Line:'1',Position:'66']
Token[Type:'StringValue',Value:'Hello World',Line:'1',Position:'78']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'79']
Token[Type:'Unknown',Value:'+-',Line:'1',Position:'80']
Token[Type:'Arithmetic',Value:'+',Line:'1',Position:'82']
Token[Type:'Arithmetic',Value:'-',Line:'1',Position:'83']
Token[Type:'Arithmetic',Value:'/',Line:'1',Position:'84']
Token[Type:'Arithmetic',Value:'*',Line:'1',Position:'85']
Token[Type:'Unknown',Value:'**',Line:'1',Position:'86']
Token[Type:'Identifier',Value:'false',Line:'1',Position:'93']
Token[Type:'Identifier',Value:'true',Line:'1',Position:'97']
Elapsed time: 31
(Ignore Position, has to be fixed in the future)
So now I do not really know a good approach to further interpret this in order to run a simple little scripting language on my own.
A good first approach is to come up with names for each thing, like "operation", "operand", "literal", "declaration" etc.
Then make a function that can read each of those from your token stream, and calls the others where appropriate. E.g. If you have:
operation: <operand> <operator> <operand>
operator: + | -
operand: <number> | <string>
etc., then you can have a function (pseudocode):
Operation parseOperation( tokens )
{
Operand operand1 = parseOperand( tokens )
Operation theOp = new Operation( tokens.fetchNextToken() )
Operand operand2 = parseOperand( tokens )
theOp.operand[0] = operand1
theOp.operand[1] = operand2
return theOp
}
and implement the other functions in a similar way. Of course, some functions may have to examine the next token to decide which other function to call, or even look ahead several tokens.
This is usually called a "recursive descent" parser.
Each of the functions returns an object that represents an operation and has its arguments hanging off of it. This is basically a tree structure, which you can then recursively walk ("depth-first").
The easiest way is to give the different object types you define dor your operations and values methods like asString() or asInt() and then do things like:
int Operation::asInt()
{
int a = operand[0].asInt()
int b = operand[1].asInt()
return a + b;
}
Objects that are already the right type (like an IntOperand class) would just return their value:
int IntOperand::asInt()
{
return self.numericValue
}
or whatever. Objects that aren't the right type either produce an error instead of returning a value, or convert themselves. So no matter how complex the expression, in the end you get an int or string or whatever out.
To run a program, you can now ask the bottom-most object for its value.

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.

"array of x is a 'variable' but is used like a method" [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 9 years ago.
Improve this question
Both instances of declarations don't work. I am a C# Novice, its obvious. I am attempting
to use a code from vb by converting to c#, I don't understand the problem so i can't fix it.
PictureBox[] pics = {picBackGround, picBackGroundTwo, picBarrier,picEnd,picFloor};
PictureBox[] pics = new PictureBox[] {picBackGround, picBackGroundTwo, picBarrier,picEnd,picFloor};
for (int i = 1; i < pics.Length; i++)
{
if (i > 3 && picUser.Bounds.IntersectsWith(pics(i).Bounds))
{
//Call CollisionDetectionRight()
}
}
You must access an array with the square brackets [] for the index.
Example.
for (int i = 1; i < pics.Length; i++)
{
if (i > 3 && picUser.Bounds.IntersectsWith(pics[i].Bounds))
{
//Call CollisionDetectionRight()
}
}
You are accessing an element of an array wrongly:
pics(i).Bounds // tries to call the undefined function pics with the parameter i, and then get the Bounds member assigned to the returned element, which may not even be returned: it could be a void - will not work; throws
As the array has been declared with the [ ] operators, you must use them to access the elements:
pics[i].Bounds // gets the value of the member Bounds of the picture at the i location of pics - will work
Working code:
for (int i = 1; i < pics.Length; i++){
if (i > 3 && picUser.Bounds.IntersectsWith(pics[i].Bounds)){
//Call CollisionDetectionRight()
}
}
Note: You should probably initialize i as 0, as that is the base of an array, not 1
You should use pics[i] to access the array. Square brackets are used to access array elements, where parentheses (()) are used for method calls.

Categories