Reputation:

How to tell what value types are initialized to by the CLR

This pertains to C# & the .NET Framework specifically.

It's best practice not to initialize the following types in the .NET framework because the CLR initializes them for you:

int, bool, etc.

and same for setting an object to null (I believe).

For example you do not need to do this and in fact it's a performance hit (drops in the bucket or not):

int Myvar = 0;

Just need int Myvar; and that's it. the CLR will initialize it to int.

I obviously just "know" from programming that int is set to 0 by default and bool to false.

And also setting an object to null because the CLR does it for you. But how can you tell what those primitive types are set to. I tried opening up Reflector to take a look at int32 and bool but could not figure out how they are initialized by default.

I looked on msdn and I don't see it there either. Maybe I'm just missing it.

Upvotes: 1

Views: 520

Answers (8)

Reputation:

http://www.codeproject.com/KB/dotnet/DontInitializeVariables.aspx

here we go. Simply: Value types are initialized to 0 and reference types are initialized to null

Upvotes: 0

regex
regex

Reputation: 3601

Try debugging the app and check to see what the initial value is prior to when you change it. There might be a better answer out there, but for the sake of closing this thread, I'm just posting a quick and dirty solution.


        static void Main(string[] args)
        {
            int iTest;
            string sTest;
            double dTest;
            bool bTest;
            float fTest;

            // stop debugger here
            Console.WriteLine();

            iTest = 0;
            sTest = "";
            dTest = 0.0;
            bTest = false;
            fTest = 0;
        }

Upvotes: 0

Rowland Shaw
Rowland Shaw

Reputation: 38130

You want a list like this one?

Upvotes: 2

arul
arul

Reputation: 14084

If you want a table, MSDN is your friend: Default Values Table (C# Reference)

Upvotes: 2

driis
driis

Reputation: 164291

You could easily make a program that prints default(T) for all T of interest.

Upvotes: 1

arul
arul

Reputation: 14084

It may be a long shot, but I'd say that

default( T )

will give you pretty accurate results.

Upvotes: 0

Gunny
Gunny

Reputation: 1166

For C#, here is the list of all the value types - click the link for each to find out what its default is:

Value Types Table (C# Reference)

Upvotes: 0

Rob Prouse
Rob Prouse

Reputation: 22647

Everything is basically zeroed out, so just take it from there. Int/Double/etc 0. String, or other structure, probably String.Empty, Guid.Empty, etc. bool, false (0 in other languages.)

It is pretty intuitive.

Upvotes: 0

Related Questions