473,583 Members | 4,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3556
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 defaultconstruc tors are not called when
declaring a local variable.

Sample:

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

//compile time error use of unassigned local variable b
//private void DoWork()
//{
// int b;
// Console.WriteLi ne(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: DoNotInitialize Unnecessarily
CheckId: CA1805
Category: Microsoft.Perfo rmance
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 PerformanceLibr ary
{
class InitializeUnnec essarily
{
bool b1;
bool b2;
int i;
double d;
string s;

InitializeUnnec essarily()
{
b1 = true;

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

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

this.s = s;
}
}
}

[Visual Basic]

Imports System

Namespace PerformanceLibr ary

Class InitializeUnnec essarily

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
3031
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 value of 0 and lets you use it anyway. My question is, how can I retrieve the default value for a given type? The CLR obviously has these defaults...
4
12304
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 changing the original variable passed)
11
5633
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
2023
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" should give me an error since variable test
10
4679
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 no-parameter constructor for my class with an empty function body. I then instantiated an object and tried printing its values, amazingly the members...
74
15931
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 creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
10
2500
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 certain circumstances the query string may not contain the variable. So I need some way of establishing a default value if one isn't set. Is...
68
4586
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 temporary but it was stated that it would not. This has come up in an irc channel but I can not find the original thread, nor can I get any code to...
7
4247
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 VB.Net Thanks
0
8179
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8323
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8191
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5700
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3816
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1431
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1155
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.