How should I interpret this int initialization? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've been programming C# for some months now but I've never encountered this till now; what does this instruction mean?
int a = 1, b;

It's same as:
int a = 1;
int b;

Above statement declare multiple variables of same datatype in single statement.
So A local variable declaration that declares multiple variables is equivalent to multiple declarations of single variables with the same type.
That means
int a=1, b;
indicates that a and b both has same data type i.e. int along with we initialize the variable a with value 1 and b has default int value i.e 0
So equivalently you can write it as
int a=1;
int b;

It depends on whether these are "locals" (method variables) or "fields" (instance variables).
For fields, it declares a and b as Int32; they are both initiaized to zero when the memory is wiped (newobj/initobj) prior to the constructor being called, and then a is assigned a value of 1 at the start of the constructor.
For locals, it declares a and b as Int32, and immediately assigns 1 to a. B has no defined value. The rules of "definite assignment" mean that it is not required to have a defined value. However, all values on the stack must have some value - and we could obtain that value by cheating (for example, writing a method in IL that implements "out", but simply dereferences the address). The actual value is Dependent on whether the init-locals flag is set. This is not a c# language feature, but the current compiler does include this flag. This means that the memory space for locals is erased (set to zero) at the start of the method. So the logical value will be zero, but for different reasons. There is no requirement for this to happen - so it is entirely an implementation detail.

It defines Integers "a" and "b" giving value 1 to a

a and b are integers
and a's value is one. b has no value yet

a was declared and initialized to zero while b was just declared.

Related

Using correct terminology: What is a "class reference" versus a "class variable"? [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 2 years ago.
Improve this question
In an effort to ensure the use of proper terminology when describing certain aspects of code, I'm asking for clarification of use in the following context:
If we write
int myIntTest;
we say "We have an int variable"
Assume that we have an Employee class, and when we write
Employee myObjectTest;
we say "We have a reference for an Employee object"
My question is:
Is it corret to say "myObjectTest is a Employee class' variable"?
I usually say "myObjectTest is a variable of type Employee" or if I want to be very specific "myObjectTest is a variable referencing an Employee instance (or null)".
I'm not sure if there's one definitive answer. Maybe somebody knows and can point you to the correct section of the specification :)
Here's what I found:
Types
Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter being known as objects.
and
Variables
Variables represent storage locations. Every variable has a type that determines what values can be stored in the variable.
So it seems like that the C# spec talks about a variable having a type. Thus, "myObjectTest is a variable of type Employee" matches the spec's language.
For the variable itself I would say it's "A variable of type Employee":
//"variable of type Employee" or
//"employee variable"
Employee e;
If an instance of the Employee class has been assigned to it I would probably say it's "an Employee instance":
//"employee instance e"
e = new Employee("John", "Smith", "Manager");
In general conversation terms between e.g. two developers you'll tend to find that the variable, as a placeholder, typically fades in importance compared to the data it holds. You might talk about variables employeeA and employeeB but what you'll actually be talking about are the Employee instances assigned to those variables - "why do employeeA and employeeB have the same name and role? Hmmm. Oh look, they're pointing to the same instance"
If you're saying something is a class variable it's a bit vague, but would probably be interpreted as "a class wide variable" - a variable that is a data member of the class. It may be best to avoid the phrase and instead use the same terms that the documentation uses for those (fields, properties, methods, constructors etc are all class members). If you're determined to use "variable" don't mention "class" - just say "Employee variable" as in "the constructor uses two Employee variables". If you're talking about variables in the specification of a method, call them parameters or arguments or say that the method "takes (class name)" - "the constructor has two Employee arguments" or "this method takes an array of Employees"
As stated, no - myObjectTest represents a variable intended to hold a reference to an instance of Employee. To say "Employee class' variable" implies a variable that belongs to the Employee class, not one that represents an instance of the class.

Why is it wrong to instantiate an object to null before instantiation? [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 6 years ago.
Improve this question
I have a situation as below:
Some class
public class Numbers
{
}
Some other class
public class Calculations
{
Numbers objNumber = null;
public void abc()
{
objNumbers = new Numbers();
}
}
What is wrong with the statement Numbers objNumber = null;?
I know I could have simply ignored the null assignment; just curious why this is wrong.
It's not wrong, it's just unnecessary, all reference types are null by default, so there is no point on initializing the variable to null because the type of the variable is a reference type.
Reference types in c#, when declared are initialized automatically with null value. So there is no difference in
Numbers objNumbers = null;
and
Numbers objNumbers;
Both will work the same. You can check this behavior by using a debugging the code.
I don't see any issue with what you are doing, just additional note types are created with default value. It won't make any difference assigning null or ignoring it.
I see just there is a typo, which you could easily identify and fix it.
There is an extra s in objNumbers, the field is defined as objNumber.
The null will be the default value for the object(reference type). So It will be null even without the assignment by you. And there is nothing wrong with that statement.
In short
Numbers objNumbers = null; and Numbers objNumbers; are same.
Consider the following example;
Numbers objNumbers = new Numbers();
objNumbers = null;
Here assignment of null make Sense
Strictly speaking it is not wrong, as the code compiles (provided you add an s to your field name).
However, there are multiple reasons this code might be unreliable from a perspective of design or correctness.
You code has a mutable field not initialized to any meaningful value: Consider the possibility that the method abc() may not get called prior to the value stored at objNumbers being accessed, which will result in a null reference exception for any likely use case.
Now consider following the null object pattern and initializing the field to an instance of this null version of the Numbers class.
That code would be much less likely to produce a null reference exception... and it would force you to think about your application's behavior in the case where accessing the field occurs prior to the execution of method abc.
For both these reasons, in my opinion, it is a favorable design discipline to avoid initializing your fields/properties to null.
Additional reading on the topic, such as this thread, shows dealing with nulls is often considered a problem in need of a solution. Initializing your code with instances and values instead of null is a start in the right direction.
Don't think much. Even though you don't assign still all objects before allocating memory are null.

Why use int, float etc. instead of object? [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 6 years ago.
Improve this question
I've been reading a book on C# and it explains that int, float, double etc. are "basic" types meaning that they store the information at the lowest level of the language, while a type such as 'object' puts information in the memory and then the program has to access this information there. I don't know exactly what this means as a beginner, though!
The book however does not explain what the difference is. Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
How does it impact the performance of the program?
This is a very broad subject, and I'm afraid your question as currently stated is prone to being put on hold as such. This answer will barely scratch the surface. Try to educate yourself more, and then you'll be able to ask a more specific question.
Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
Basically you use the appropriate types to store different types of information in order to execute useful operations on them.
Just as you don't "add" two objects, you can't get the substring of a number.
So:
int foo = 42;
int bar = 21;
int fooBar = foo + bar;
This won't work if you declared the variables as object. You can do an addition because the numeric types have mathematical operators defined on them, such as the + operator.
You can refer to an integer type as an object (or any type really, as in C# everything inherits from object):
object foo = 42;
However now you won't be able to add this foo to another number. It is said to be a boxed value type.
Where exactly these different types are stored is a different subject altoghether, about which a lot has been written already. See for example Why are Value Types created on the Stack and Reference Types created on the Heap?. Also relevant is the difference between value types and reference types, as pointed out in the comments.
C# is a strongly typed language, which means that the compiler checks that the types of the variables and methods that you use are always consistent. This is what prevents you from writing things like this:
void PrintOrder(Order order)
{
...
}
PrintOrder("Hello world");
because it would make no sense.
If you just use object everywhere, the compiler can't check anything. And anyway, it wouldn't let you access the members of the actual type, because it doesn't know that they exist. For instance, this works:
OrderPrinter printer = new OrderPrinter();
printer.PrintOrder(myOrder);
But this doesn't
object printer = new OrderPrinter();
printer.PrintOrder(myOrder);
because there is no PrintOrder method defined in the class Object.
This can seem constraining if you come from a loosely-typed language, but you'll come to appreciate it, because it lets you detect lots of potential errors at compile time, rather than at runtime.
What the book is referring to is basically the difference between value types (int, float, struct, etc) and reference types (string, object, etc).
Value types store the content in a memory allocated on the stack which is efficient where as reference types (almost anything that can have the null value) store the address where data is. Reference types are allocated on the heap which is less efficient than the stack because there is a cost to allocating and deallocating the memory used to store your data. (and it's only deallocated by the garbage collector)
So if you are using object every time it will be slower to allocate the memory and slower to reclaim it.
Documentation

Why isn't this allowed in C#? [closed]

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 have the following if condition param.days is a string.
if (param.days != null)
This works fine, but if I say
If (param.days)
then it does not evaluate correctly at runtime. Both statements are not the same in C#.
It does say that the value is null but then C# tries to cast it to a bool which is non-nullable.
Why did the C# designers choose to do it this way?
Such a statement is valid in C++, but why is this not considered valid in C#?
Such a statement is valid in C++, but why is this not considered valid in C#
Because C# assumes different languange rules. It does not assume that every number / reference can be treated as a boolean by checking if it is zero vs non-zero, null vs non-null. If you want to test whether something is null: test whether it is null.
Note: if days is actually a T? (aka Nullable<T>), then you can check:
if(param.days.HasValue)
which is then identical to if(param.days != null)
Alternatively, if your type can sensibly be treated as a boolean, then there are operators you can override to tell the compiler that.
C# unlike C++, does not implicitly cast integer to bool.
To clarify, this is answering the question amendment in the comments: why did the C# designers choose not to implement null to boolean evaluation whereas C++ allows it.
Taken from Eric Lippert's post "null is not false":
Some languages allow null values of value types or reference types, or
both, to be implicitly treated as Booleans.
And similarly for nullable value types; in some languages a null value
type is implicitly treated as "false".
The designers of C# considered those features and rejected them.
First, because treating references or nullable value types as Booleans
is a confusing idiom and a potential rich source of bugs. And second,
because semantically it seems presumptuous to automatically translate
null -- which should mean "this value is missing" or "this value is
unknown" -- to "this value is logically false".
This particular sentence covers your string example, but nothing of other types having implicit boolean evaluation.
However, one might surmise the reason for items such as integers not evaluating to boolean also falls under the banner of being a poor idiom or too presumptuous.
The comparison in the if statement needs to evaluate to a boolean result. param.days is not a boolean. You need to compare the value to null to get a boolean result. C# is type safe.
In C#, the If statement requires the contents of the brackers to be a boolean expression.
Consider If ("Hello World").
Is "Hello World" true or false? It's neither, it's a string.
You may want to consider a LINQ expression such as .Any() for example, If (myListOfCats.Any()) as your .days property implies a collection of objects.
The comparison in the if statement requires to a boolean result. param.days is string not a boolean. C# does not implicitly cast integer to bool.
You need to compare the value to null or use string.IsNullOrEmpty() to get a boolean result
If you want to do so try this code:
if (!string.IsNullOrEmpty(param.days))
{
}
OR
if (param.days!=NULL)
{
}

How Value types stored? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where are .NET local variables stored?
function storeonstack()
{
int a;
int b;
int c;
a=1;
b=1;
a=2
c=2;
}
Can Some body explain me how these value types are stored on stack?
Practically speaking*, value types are stored on the stack if they are local variables within a method, or on the heap if they are members of a reference type. Sometimes, local variables may also be stored on the heap if they are included in a closure. This is required so that the variables can continue to live after the function exits (and the stack frame is cleaned up). Local variables may also be stored in registers when they are used in operations, before being spilled back to the stack. Depending on JIT optimizations, local variables may only exist in registers, or may not exist at all. Member variables should always exist, though.
*Yes, technically, there's no guarantee that things like stack and heap exist, but let's be honest, on most, if not all, .NET implementations, there is a stack and a heap as in C programs.
It is an implementation detail and depends upon compiler. It may vary from compiler to compiler.
The Truth About Value Types
The stack is an implementation detail

Categories