Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename "value" variable in set accessor of a property in C#

Tags:

c#

.net

vb.net

IN VB.NET you can change the name of this variable. Can you do this in C# too or is it always called value?

Example:

    Private _SomeVariable As String
    Public Property SomeValue() As String
        Get
            Return _SomeVariable
        End Get
        Set(ByVal foo As String) ' This is what I mean
            _SomeVariable = foo
        End Set
    End Property

I'm used to write code in VB.NET, but want to change to C# eventually and trying to learn all the differences and peculiarities of C#.

I know this is no big deal, but Telerik for example isn't aware of it while converting VB.NET to C#, which could lead to a missbehaviour in case you have a class variable named foo too (for the above-mentioned example).

like image 608
keco Avatar asked Dec 10 '25 07:12

keco


2 Answers

The set parameter is always named value, and you cannot change it. If you happen to have a conflicting name in your code, you can use the fully-qualified name in order to use it:

class MyClass
{
    private string value;

    public string Value
    {
        get { return value; }
        set { this.value = value; }  // this.value is the private field
    }
}
like image 93
Rufus L Avatar answered Dec 12 '25 21:12

Rufus L


In C#, the new value is always accessed via value. There is no syntax to write a setter to accept a custom name.

See Using Properties (C# Programming Guide).

The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property ..

like image 45
user2864740 Avatar answered Dec 12 '25 20:12

user2864740



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!