In c# in properties of classes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In c# in properties of classes

Why we cannot write any word in the place of value in set accessor

1st Apr 2020, 4:31 AM
Quantumspark
Quantumspark - avatar
2 Answers
+ 3
Quantumspark The set parameter in C# can't be changed because it isn't explicitly declared. VB.NET does explicitly declare the set parameter allowing it to be renamed as seen below. -------- Class Foo   Private _age As Integer = 0   Public Property Age As Integer     Get Return _age End Get 'Set explicitly declares the Set parameter.     Set(ByVal age As Integer)       _age = age     End Set   End Property End Class ---- Compared to C# below: -------- class Foo {   private int _age = 0;   public int Age {     get => _age;     set => _age = value;   } } ---- The C# version compiles to IL as if it was: -------- void set_Age(int value) { _age = value; }
27th Apr 2020, 6:15 AM
David Carroll
David Carroll - avatar
+ 1
If by "word" you mean a string, you can do this if the field is of type string, though it wouldn't make any sense to do this, since the argument stored in the setter's "value" parameter wouldn't be set as the field's value (assuming you're using a field), but rather the regular string value you're using in place of the "value" argument. For example: /* This code allows the Thing.Stuff property to read and write values for the _stuff field. Any value stored in the _stuff field can be read reliably. */ public class Thing { private string _stuff; public string Stuff { get { return _stuff; } set { _stuff = value; } } } /* This code has the _stuff field always storing the string value "hotdog", no matter what the "value" argument is when the setter is invoked. "hotdog" is always the string value being assigned to the _stuff field. This makes no sense to do. */ public class Thing { private string _stuff; public string Stuff { get { return _stuff; } set { _stuff = "hotdog"; } } }
27th Apr 2020, 2:47 AM
Shane Overby
Shane Overby - avatar