What is the default value of a primitive type variable in C#?

Asked

Viewed 299 times

1

When a primitive type variable is created but not initialized its value is null?

Example:

public int x;

If I don’t do anything with x, which means I don’t assign a value to it, it will be null?

  • 4

    Which programming language?

  • Define primitive type

  • 3

    This is not about programming logic. This is a specific behavior that depends on each language.

  • 1

    Each language has a different behavior for initializing variables. Needs to specify which language you refer to.

  • Assuming the tag is correct and the doubt is about C#, see here the default values for each type: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table

  • A statement with no explicit value will not make the variable usable until a value is assigned to it in C#.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

Show 2 more comments

1 answer

3

C# does not have so-called primitive types, these types said in the question are by value. Their default value is usually 0, each with its 0 representation.

The null is a reference with a value of 0, so it has no object associated with it. Only types per reference can be effectively null, so one type per value cannot be null. Then one type per reference will be null.

There are even types that simulate nullity, for example a int? may be null, but in practice it is only a composition indicating nullity, and has undesirable side effects.

In the construction of the object this variable will be zeroed. In local variables will not compile, it is mandatory to put a value, even if it is the default value, you can even use default instead of the value, if it is the most appropriate semantics. Since it is clear that the type is not being inferred.

In C# 8 the use of nulls is discouraged. It serves much better than it already is as a valid alternative to exceptions in flow control (which is the wrong mechanism).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.