473,395 Members | 1,411 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Default value of basic variable type

i am a newbie,
i remember i read a book talking about when u declare a array variable
using
float[] ABC = new float[10];

the whole array element in ABC ( ABC[0] to ABC[9] ) will automatic
initialize to 0
and all type of numeric variable is initialize to 0, bool type is false,

is it true?

i can't find the book now, can u please telling me?

THANKS
Aug 16 '07 #1
4 3536
Macneed wrote:
i am a newbie,
i remember i read a book talking about when u declare a array variable
using
float[] ABC = new float[10];

the whole array element in ABC ( ABC[0] to ABC[9] ) will automatic
initialize to 0
and all type of numeric variable is initialize to 0, bool type is false,

is it true?
In an instance of a class, yes. So all the floats in a "new float[10]"
get initialized to the default value for the float (0). Likewise, all
the bools in a "new bool[10]" get initialized to false.

Note, however, that a stack variable is not initialized. You're
required to initialize it explicitly before you use it. The compiler
generates an error if you attempt to use the variable before you
initialize it (and in many cases, even if you do, if you're not clear
enough to suit the compiler :) ).

Pete
Aug 16 '07 #2
Yes and no.

all value types have a devault constructor that initalizes the value
to 0.
See: http://download.microsoft.com/downlo...cification.doc
Section: 4.1.2

But be carefull these defaultconstructors are not called when
declaring a local variable.

Sample:

class A
{
int a;
public A()
{
Console.WriteLine(a);
}

//compile time error use of unassigned local variable b
//private void DoWork()
//{
// int b;
// Console.WriteLine(b);
//}
}

Aug 16 '07 #3
Yes
This is part of the language spec (ECMA-334, 3rd edition):

§19.2 Array creation
Elements of arrays created by array-creation-expressions are always
initialized to their default value
(§12.2).
§12.2 Default values
* For a variable of a value-type, the default value is the same as the
value computed by the value-type's
default constructor (§11.1.2).
* For a variable of a reference-type, the default value is null.
§ 11.1.2 Default constructors
All value types implicitly declare a public parameterless instance
constructor called the default constructor.
The default constructor returns a zero-initialized instance known as
the default value for the value type:
* For all simple-types, the default value is the value produced by a
bit pattern of all zeros:
* For sbyte, byte, short, ushort, int, uint, long, and ulong, the
default value is 0.
* For char, the default value is '\x0000'.
* For float, the default value is 0.0f.
* For double, the default value is 0.0d.
* For decimal, the default value is 0m.
* For bool, the default value is false.
* For an enum-type E, the default value is 0.
* For a struct-type, the default value is the value produced by
setting all value type fields to their default
value and all reference type fields to null.
Aug 16 '07 #4
Using fxcop rules dealt on that.

The rule name is : "Do not initialize unnecessarily"
================================

Rule Description :

Do not initialize unnecessarily
TypeName: DoNotInitializeUnnecessarily
CheckId: CA1805
Category: Microsoft.Performance
Message Level: Warning
Certainty: 90%
Breaking Change: NonBreaking

Cause: A static or instance constructor initializes a field to its default
value. This rule ignores Managed C++ assemblies.

Rule Description
The common language runtime initializes all fields to their default values
before running the constructor. In most cases, initializing a field to its
default value in a constructor is redundant, which degrades performance and
adds to maintenance costs. One case where it is not redundant occurs when the
constructor calls another constructor of the same class or a base class
constructor and that constructor initializes the field to a non-default
value. In this case, changing the value of the field back to its default
value can be appropriate.

How to Fix Violations
To fix a violation of this rule, remove the field initialization from the
constructor. Note that the C# compiler that is included with .NET Framework
version 2.0 removes these unnecessary initializations when the optimize
option is enabled.

When to Exclude Messages
Exclude a message from this rule if the constructor calls another
constructor in the same or base class that initializes the field to a
non-default value. It is also safe to exclude a message from this rule, or
disable the rule entirely, if performance and code maintenance are not
priorities.

Example Code
The following example shows a type that contains multiple violations of the
rule.

[C#]

using System;

namespace PerformanceLibrary
{
class InitializeUnnecessarily
{
bool b1;
bool b2;
int i;
double d;
string s;

InitializeUnnecessarily()
{
b1 = true;

// The following field assignments are violations of this rule.
b2 = false;
i = 0;
d = 0;
s = null;
}

InitializeUnnecessarily(string s) : this()
{
// Exclude the warning for the following statement.
b1 = false;

this.s = s;
}
}
}

[Visual Basic]

Imports System

Namespace PerformanceLibrary

Class InitializeUnnecessarily

Dim b1 As Boolean
Dim b2 As Boolean
Dim i As Integer
Dim d As Double
Dim s As String

Sub New()

b1 = True

' The following field assignments are violations of this rule.
b2 = False
i = 0
d = 0
s = Nothing

End Sub

Sub New(s As String)

Me.New()

' Exclude the warning for the following statement.
b1 = False

Me.s = s

End Sub

End Class

End Namespace
--
Sincerely
Yaron Karni
http://dotnetbible.blogspot.com/
"Macneed" wrote:
i am a newbie,
i remember i read a book talking about when u declare a array variable
using
float[] ABC = new float[10];

the whole array element in ABC ( ABC[0] to ABC[9] ) will automatic
initialize to 0
and all type of numeric variable is initialize to 0, bool type is false,

is it true?

i can't find the book now, can u please telling me?

THANKS
Aug 17 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
by: John Wood | last post by:
Even though CSC does its best to detect use of unassigned variables, it often misses it... for example if you just declare a double in a class without assigning a default value, it has a default...
4
by: Carlos Gomez | last post by:
In VB6 the default for passing variables was ByRef. It was faster and used less memory. Why did MS changed that? Are there any advantages using ByVal over ByRef? (other than ByVal impeding you from...
11
by: prefersgolfing | last post by:
I'm trying to find on MSDN, or someplace, that speaks to variables being public or private by default. Anyone know where? Thanks.
7
by: Justin | last post by:
Is there any way to prevent VB.net to give default value to a variable (changing settings what not...)? For example Dim test As Integer test = test + 1 the statement "test = test + 1"...
10
by: Joel | last post by:
Is it true that if we don't specify a default constructor for our class, then the C# compiler provides us with its own that zeroes (or assigns default values) to the data members? I wrote a...
74
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the...
10
by: Brad Baker | last post by:
I have an asp.net/csharp application that requires a particular variable to work properly. This variable is usually passed via a query string in the URL when the application is first run but under...
68
by: Jim Langston | last post by:
I remember there was a thread a while back that was talking about using the return value of a function as a reference where I had thought the reference would become invalidated because it was a...
7
by: =?Utf-8?B?Y291Z2FyaXN0aWM=?= | last post by:
I am trying to convert an C# application to VB and have one issue which is converting the generic value to the default. C# uses return default(T) as the return value how would I translate this in...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.