msmolcic
msmolcic

Reputation: 6557

Declaring and initializing structure variables

This will be a quick question. I don't quite understand why this is happening so I'll show you what's bothering me through simple examples..

First example:

private static Point pt;

public static void Main(string[] args)
{
    pt.Display();
}

public struct Point
{
    public int X;
    public int Y;

    public void Display()
    {
        Console.WriteLine("X = {0}, Y = {1}", X, Y);
    }
}

Second example:

public static void Main(string[] args)
{
    Point pt;
    pt.Display();
}

public struct Point
{
    public int X;
    public int Y;

    public void Display()
    {
        Console.WriteLine("X = {0}, Y = {1}", X, Y);
    }
}

I may be missing something obvious, but first example compiles right and I get output on a console, and in the second example it won't even compile because:

Local variable 'pt' might not be initialized before accessing.

Well, it's not initialized in the first case either, but it does the job, what's the point?

P.S. No pun intended.

Upvotes: 0

Views: 167

Answers (2)

D Stanley
D Stanley

Reputation: 152556

Class members that aren't initialized won't cause that compiler error because their scope is too broad for the compiler to determine if it could be initialized somewhere else. It could be initialized in the the constructor, in any other class method, or even externally if it's public. With a variable declared in local scope, the compiler can easily determine if the variable is initialized before it's used or not.

The "default" value for a struct is a struct with each of its fields set to the default value for it's type, so you effectively get a point with X and Y values of (0,0).

If you had declared Point as a class instead of a struct you'd have gotten a NullReferenceException at runtime because the reference would have a null value when you call pt.Display().

Upvotes: 2

Selman Genç
Selman Genç

Reputation: 101681

In the first case it's a static field and it will be automatically initialized by the compiler. In second case it's a local variable and you are responsible of initializing it, not the compiler.

Upvotes: 3

Related Questions