Is it a breaking change that modifying the access modifier of a public property?

前端 未结 5 827
太阳男子
太阳男子 2021-02-01 05:22

If I change the access modifier of the setter of a public property from private to public, is that causes any breaking change in the other assemblies that refer it?

5条回答
  •  礼貌的吻别
    2021-02-01 05:58

    It is a breaking change, in that it may cause existing code to no longer compile.

    Some languages do not allow you to override a property without overriding all visible accessors. VB is such a language.

    Say you have the following C# class:

    namespace TestLibrary
        public class A {
            public virtual int X { 
                get { return 0; } 
                private set { Console.WriteLine("A.set_X called."); } 
            }
        }
    }
    

    In a VB project that references your library, you have a class definition:

    Class B : Inherits TestLibrary.A
        Public Overrides ReadOnly Property X As Integer
            Get
                Return MyBase.X
            End Get
        End Property
    End Class
    

    Notice the ReadOnly modifier on the property. This is required in VB, because you are only defining the getter. If you leave it out, you get a compile-time error:

    Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.

    Now, remove the private modifier from the setter in your C# class:

    namespace TestLibrary
        public class A {
            public virtual int X { 
                get { return 0; } 
                set { Console.WriteLine("A.set_X called."); } 
            }
        }
    }
    

    You will now get a compile-time error in your VB code:

    'Public Overrides ReadOnly Property X As Integer' cannot override 'Public Overridable Property X As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.

    The same code that references your library does not compile after you make the change, so it is a breaking change.

提交回复
热议问题