3

Got to know a new thing today that we can create integers by using new operator as below

int num = new int();

Now I wonder if I create an integer in this manner then the resulting integer will be a value type or reference type? I guess it will be a value type. I tried the below code

int num1 = 10;
int num2 = new int();
int num3;
num1 = num2;
num2 = num3;

I got the below build error:

Use of unassigned local variable 'num3'

I know why this build error is given. But I wonder when and how to use new int() and how exactly does this work? Can anyone please put some light on this?

Thanks & Regards :)

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Narendra
  • 3,069
  • 7
  • 30
  • 51
  • 9
    `int i = new int()` and `int i = 0` produce exactly the same **IL**, so there is no difference, only from the compiler's perspective. Literal notation seems to be much more friendly, so I would recommend to stick with it and don't bother about calling `int` constructor explicitly. – Ilya Ivanov Jun 17 '13 at 12:33
  • `default(int)` is also the same as `new int()` and `0` (in this context). The default constructor of a struct (which is `new T()` or `default(T)`) is, as I understand it, simply all zeroes in the bytes that make up the struct. With an `int`, that means `0`. – Tim S. Jun 17 '13 at 12:38
  • For more advanced stuff, see http://stackoverflow.com/questions/9207488/what-does-the-keyword-new-does-to-a-struct-in-c – nawfal Jun 17 '13 at 12:44
  • possible duplicate of [Where and why use int a=new int?](http://stackoverflow.com/questions/5746873/where-and-why-use-int-a-new-int) – nawfal Jun 18 '13 at 09:03

3 Answers3

5
int i = new int();

is equavalent to

int i = 0;

There is no difference between them. They will generate the same IL code at all.

  // Code size       4 (0x4)
  .maxstack  1
  .locals init ([0] int32 num)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ret

From Using Constructors (C# Programming Guide)

Constructors for struct types resemble class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default values.

Default value of integers is 0. Check for more Default Values Table

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

The answer is in section 4.1.2 of the C# language spec:

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:

Like any other instance constructor, the default constructor of a value type is invoked using the new operator. For efficiency reasons, this requirement is not intended to actually have the implementation generate a constructor call. In the example below, variables i and j are both initialized to zero.

class A
{
    void F() {
        int i = 0;
        int j = new int();
    }
}

In terms of doing things without using a default constructor, such as

int x = 1;

That's covered by section 4.1.4 of the C# Language Spec:

Most simple types permit values to be created by writing literals (§2.4.4). For example, 123 is a literal of type int

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

I think, you are looking for

int num = default(int);

This is also useful when facing compilation error, Unassigned local variable

wuhcwdc
  • 286
  • 1
  • 10
  • `int num = default(int);` - what a confusion for maintaining team. – Ilya Ivanov Jun 17 '13 at 12:35
  • `default(int)` is silly. The default keyword is only useful when dealing with generic types: `default(T)`. – Steven Jun 17 '13 at 12:37
  • @IlyaIvanov : What do u mean ? – wuhcwdc Jun 17 '13 at 12:38
  • @PankajGarg Steven makes a good point. I was talking about confusion, that the developers will encounter, when they will meet you're initialization. Compiler will optimize `int num = default(int);` call to `int num = 0;` so why to bother at all with `default` keyword? – Ilya Ivanov Jun 17 '13 at 12:40
  • @llyalvanov - Why do we need `default(int)` then ? – wuhcwdc Jun 17 '13 at 12:50
  • 1
    @IlyaIvanov I love the use of `default(int)`. Its gives you a consistent style (with classes) and makes your intent clear. If I want 0 for my variable, I assign a zero. If I want just an assignment whose value I don't care about initially, I use `default(int)` – nawfal Jun 17 '13 at 13:03
  • 1
    @nawfal what's the point of `default(int)`? Why not to save your and peer's time and write just `0`? What are the semantics, which you add when you write `default(int)`? Does it indicate, that you don't care about the value? Why not to extract creation into separate method and give it a **meaningful** name, like `CreateNumberIDontCareOf` or `ExtractNumberFromTheDeepEdgesOfBurningHell`? What if you change your domain default value from zero to one, should you also change all calls to `default(int)`, which is by definition more difficult, than changing `0` to `1` in one place or even multiple. – Ilya Ivanov Jun 17 '13 at 13:22
  • @IlyaIvanov *//Why not to save your and peer's time and write just 0?//* As I said intent is the key, not time. ymmv. – nawfal Jun 17 '13 at 13:43
  • @IlyaIvanov *//Why not to extract creation into separate method and give it a meaningful name, like CreateNumberIDontCareOf or ExtractNumberFromTheDeepEdgesOfBurningHell?//* U din get me. I'm not talkin of those cases that warrant a refactoring. Think about `bool b` I have to declare outside a `foreach` loop to access inside the loop to check some condition? There are plenty of times you have to initialize it just to get it compiled. Think of how u're saved typing when you declare just `bool b` as a member variable. All the initialization is done at runtime automatically. I'm talkin of those. – nawfal Jun 17 '13 at 13:44
  • *//What if you change your domain default value from zero to one, should you also change all calls to default(int), which is by definition more difficult, than changing 0 to 1 in one place or even multiple.//* I have no idea what you're talking about. All I have to say is I'm not talking of a domain value that may require a change later. I'm talking of something a lot simpler than all that. – nawfal Jun 17 '13 at 13:45
  • @nawfal How on earth did you get so high reputation? `int num = default(int);` doesn't make your intention any cleaner, in fact, it makes it much less obvious. Just write `int num;`, takes least time to write and is easiest to understand. If you want, go with `int num = 0;` but never `default(int)` or `new int()` –  Jun 17 '13 at 21:00
  • @MarkusMeskanen its sad that you just make a *statement* without replying specifically to the points I made. One last effort: *//int num = default(int); doesn't make your intention any cleaner//* not cleaner, I said clearer. *//it makes it much less obvious//* I have two ways of representing two things, you have one. If that is more obvious for you, then ymmv. *//Just write int num;//* My compiler shouts (and sensibly of course) at times over this. I made it clear last time. – nawfal Jun 18 '13 at 07:45
  • Lastly, you don't see my code base littered with `default` keyword. I use `0` to good use since that's what mostly I need. I was talking of such rare cases where I prefer one style (so rare that you might have never needed one). – nawfal Jun 18 '13 at 07:47
  • @nawfal You didn't make any reasonable statements, that's why I ignored them. It's sad that you tend to waste everyone's time by writing `default(int)` instead of `0`. So, why would I need two ways to represent something, if the second way is much less effective, takes more time, looks more complicated and is never required? And the thing is, there's no case where you'd benefit from writing `default(int)`. I often write `int i = new int(default(int));`, but it's such a rare (and advanced) case that beginners like you would probably never need to do it. *NO*, nobody needs to do this. Period. –  Jun 18 '13 at 08:19
  • *//You didn't make any reasonable statements, that's why I ignored them.//* If it wasn't reasonable, question that, rather than ignoring and re-ask the same thing. *//So, why would I need two ways to represent something//* Because they are two different things according to my semantics. Saying a third time. *//I often write int i = new int(default(int))//* Ok what does this do? – nawfal Jun 18 '13 at 08:53