简体   繁体   中英

Compile error using C# automatically implemented properties

AC# Noob, I am trying to use SharpDevelop utility to convert my VB.NET application a C#.

I am noticing that my automatically implemented properties are generating a lot of errors. For example, take the following property:

public SqlDateTime DateOfBirth { get; set; }

Whenever I try to access the implied underlying module level variable, _DateOfBirth, I get the error.

Error 699 The name '_DateOfBirth' does not exist in the current context D:\\Users\\Chad\\Desktop\\BESI CSharp\\BESI\\BESI.BusinessObjects.ConvertedToC#\\ChinaVisa.cs 240 13 Besi.BusinessObjects.Converted

I could expand the properties declarations out to full-fledged properties, but this should n't be necessary and I'd like to understand why I am getting this error.

You cannot access the compiler-created backing variable - you must use the property. The compiler-generated backing field is specifically named in such a way to prevent you from accessing it (it is not named _DateOfBirth , it is named something like <DateOfBirth>k__BackingField ).

Access the property directly - if you need to manipulate the backing field directly then don't use an automatically implemented property.

Just a side note - it doesn't matter what the property name is (it is an implementation detail and could change on different versions of the compiler or with different compiler implementations altogether). The field is given an identifier that is specifically designed to meet the naming restrictions of the CLR but fail the naming restrictions of C# making it impossible to ever write straight C# code that accesses that variable directly.

Also remember that automatically implemented properties are not public fields. They are a shorthand that the compiler expands for you (sort of like a macro).

So this class:

class Bar
{
    public object Foo { get; set; }
}

Gets expanded to this:

class Bar
{
    [CompilerGenerated]
    private object <Foo>k__BackingField;

    public object Foo
    {
        [CompilerGenerated]
        get
        {
            return this.<Foo>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<Foo>k__BackingField = value;
        }
    }
}

It is still a full property - you are simply allowing the compiler to write the getters and setters for you.

If you use automatically generated properties, you cannot rely on the compiler picking any specific name for the backing field. That's entirely compiler-specific, and even if you could access those fields, your code might still break if you use another compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM