Warnings and classes

Hi!

I'm new here and i've begun to learn C#.

I have Microsoft Visual Studio 2005,and I think I found some bugs:

1.

class Car

{

public int Year;

}

Why does this code create a warning (Field 'Car.Year' is never assigned to, and will always have its default value 0)

Now this warning should be ONLY with unpublic fieds in structs and classes (written in MSDN - here's the link http://msdn2.microsoft.com/en-us/library/03b5270t(VS.80).aspx) and Year is public!

Is this a bug

2.

When I compile code and having warnings, so when I hit the 'build' button again they just disappear!

Strange...

Thank you very much for the help!



Answer this question

Warnings and classes

  • Jyothi G

    Well the class (Car) is effectively internal, so Year can only be changed by code in your project. Since the compiler can detect that the field is never assiegned anywhere in the project you get the warning. It will go away as soon as you start using it.



  • AJ-VENNING

    Yes it matters. If the class was public, the compiler wouldn't know if the field was used by some other project. As long as the class is non-public, the field is only accessible from within the same project (or assembly), where the compiler can determine for sure whether or not the field is being used.



  • Leaf.

    Ahhh!

    Now I understand,thank you both!

    C# ROCKS!


  • Thams

    Yes, it matters that the class isn't public. The only way to access the "Year" field is from an instance of the "Car" class. However, as the "Car" class is not public, it can only be instantiated within your project/assembly. Thus the compiler knows everything about how the "Car" class is used, and by extension, how the "Year" field is used, and can state with absolute certainty whether it is ever assigned to or accessed. As a field that is never  assigned to or accessed is quite useless and probably a mistake, the compiler generates this warning.

    -Tom Meschter
    Software Dev, Visual C# IDE



  • Silaros

    But does it metter that the class isn't public

    I wrote PUBLIC INT,and the Integer variable is public..

    I don't understand how internal or private class makes this warning message.

    Thank you.


  • Bardia Hamedani

    I still don't understand why I get this warning..

    Thank you.


  • Warnings and classes