2

The C# compiler rejects the use of an un-assigned int. However using an int via a class is not forbidden. Why that difference? And why not allow the use of un-initialized variables as they are guaranteed to be zero?

class Program
{
    class MyInt { public int I; }
    static void Main(string[] args)
    {
        MyInt mi = new MyInt();
        Console.WriteLine(mi.I);// accepted by the compiler
        int i;
        Console.WriteLine(i); // rejected by the compiler
    }
}
Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • You want 'The spec says it's forbidden' answer, or do you want to know why the decision was made to ban that kind of usages? – MarcinJuraszek Jan 12 '15 at 08:33
  • This one gives you the answer: http://stackoverflow.com/a/8933935/1163867 – MarcinJuraszek Jan 12 '15 at 08:39
  • 1
    @Rawling, This is definitely not a duplicate. The other answer doesn't provide explanation as to why instance fields are indeed considered as initialized. – haim770 Jan 12 '15 at 08:39
  • Non-initialized value types are allowed under some circumstances, for example in combination with an out parameter reference. – Magnus Jan 12 '15 at 08:40
  • @haim770 http://stackoverflow.com/a/8933935/251311 – zerkms Jan 12 '15 at 08:40
  • @haim770 Whatever. The best answer you're going to get is "because the spec says so". I'm not sure how many different variations of that question/answer we need. – Rawling Jan 12 '15 at 08:41
  • 2
    @Rawling There is an answer provided by Eric (the one I linked to closing as duplicate), who was on C# team at Microsoft for quite a long time. – MarcinJuraszek Jan 12 '15 at 08:42
  • @MarcinJuraszek Yeah I like that one, but I blew my Mjolnir usage too soon :) – Rawling Jan 12 '15 at 08:44
  • Shit, I had a 4 paragraph answer and I thought it could add value. – Matías Fidemraizer Jan 12 '15 at 08:46
  • @Rawling i've seen some questions that are marked as multiple duplicates. Maybe you are able to mark it as duplicate again (or are maybe those questions simply edited to contain the multiple duplicates)? – default Jan 12 '15 at 08:47
  • @MatíasFidemraizer you can probably add it to the duplicated questions. – default Jan 12 '15 at 08:47
  • 1
    @Default I can't do that - I think those are questions that got five votes to close as duplicate but for different questions. Marcin's choice is better than mine was anyway. – Rawling Jan 12 '15 at 08:49
  • I'm not agree to mark this question as duplicate. The question is about a difference and the linked answer do not talk about the difference between local variables and class member. – Orace Jan 12 '15 at 08:49
  • @Default I'm not sure if it would add actual value my answer. It was a speculation – Matías Fidemraizer Jan 12 '15 at 08:50

0 Answers0