CS0188 Error in Structure - c#

Take a look at this code.
public struct Customer
{
private int _id;
private string _name;
public int Id
{
get { return this._id; }
set { this._id = value; }
}
public Customer(int Id, string Name)
{
this.Id = Id; // Error - CS0188: The 'this' object cannot be used before all of its fields are assigned to.
this._name = Name;
}
}
`
Why do I get this error on the above line.
Now look at this code.
public struct Customer
{
private string _name;
public int Id { get; set; }
public Customer(int Id, string Name)
{
this.Id = Id; // No error recieved.
this._name = Name;
}
}
In the above code I implemented Id as an Auto-Implemented property.
This time I don't get any errors. Why?
Just to make it clear following link does not have my answer.
Compilation error. Using properties with struct

You need to initialize all the fields of struct first. When you assign a value to an Auto-Implemented property it always sets the backing field, however, with custom setters, it's not always guaranteed. That's why you don't get any error
For custom properties:
public struct Customer
{
private int _id;
private string _name;
public int Id
{
get { return this._id; }
set { this._id = value; }
}
public Customer(int Id, string Name)
{
_id=0;
this._name = Name;
this.Id = Id; // This will work now
}
}

Under C# 5, both methods should generate an error. From Automatically Implemented Properties:
This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.
However, C# 6 introduced read-only auto-implemented properties and introduced this language (whilst removing the above language):
a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.
I suspect that they changed all assignments for Automatically Implemented Properties (not just for readonly) in constructors to assign to the backing field rather than use the accessor. This is known to be "safe" since the accessor doesn't contain any custom code - unlike the situation in your first example where the set accessor could do anything, including leaking the not-definitely-assigned this outside of the current struct.

Related

Why is it not allowed to have only one accessor with a body instead of two?

Assume I had this property:
public int Money
{
get;
set{
Money = value;
}
}
This won't compile, saying that the get accessor must have a body because it is not marked abstract, extern or partial. If I add a body to it and return the Money property like so:
public int Money
{
get{
return Money;
}
set{
Money = value;
}
}
.. I'll have an infinite loop on my hands and my program will throw a stack overflow exception.
So my question ultimately boils down to: Is there a way I can keep the get/set accessors, return the current value in get without creating an infinite loop, and still have a body for the set accessor?
Either use:
public int Money { get; set; }
or if you really need to have a body for accessors, you need to use a backing field:
private int _money;
public int Money
{
get { return _money; }
set { _money = value; }
}
However, the latter is only used if you need to perform some additional logic (e.g. raise an event) when getter or setter is used.
Also, the latter is more or less what the compiler generates for you automatically and it can ensure that the backing field is used consistently.
If you provide only one body, it becomes hard to define how should it behave: after all you don't have access to the generated backing field in your code so the whole idea doesn't make sense.
If you declare a body for one of the accessors, you're not dealing with an auto-implemented property anymore and need to implement the other accessor as well.
This is an auto-implemented property:
public int Foo { get; set; }
Which will generate a backing field when compiled. It will represent something like this in IL:
private int BackingField_Foo;
public int Foo
{
get { return BackingField_Foo; }
set { BackingField_Foo = value; }
}
In the case of an auto-implemented property, the compiler generates the field, so it knows where to read and write the value - but you can't access it.
Now if you implement one of the accessors yourself, to write to a self-defined field yourself, it's not an auto-implemented property anymore, so you'll have to implement the other accessor as well (as long as you declare it; you can create a regular read- or write-only property just fine).
Your current code throws StackOverflowExceptions because the accessors access themselves, ad infinitum.
See also Correct use of C# properties.
You can do the one of the following:
// 1. a public variable
public int Money;
// 2. an auto-implemented, or implicit property (very much like the above)
public int Money { get; set; }
// 3. An explicit property declaration with a private variable
private int _money;
public int Money {
get {return _money;}
set {
_money = value;
// possibly do something else here
}
}

C# Best practices - Set readonly model property value from BLL

Consider the below:
public class Project.Model.ModelName : BaseClass
{
private int _id;
private string _name;
public int ID
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
}
}
public class Project.BLL.ModelName
{
public static string ComputeName(Model.ModelName m)
{
// Determine value using complex business logic
return "Whatever";
}
public static bool SetName(Model.ModelName m)
{
string Name = ComputeName(m);
// How can I set the ModelName.Name value here?
m.Name = ??? // No set accessor
}
}
I have a model with a string property that only has a get accessor, we do not want the value to be set directly.
The value for the property is computed in the BLL, a different library.
What's the best way to set the value of the property without using reflection?
For clarification, the challenge is that the Name value needs to be immutable. The same model is frequently accessed and modified. We did not want to risk someone assigning a value to it after the fact. I guess I'm looking for a best practice to maintain immutability.
ModelName.Name property only have a getter specified on _name. There is no way you it can be altered as it is. The only way to do it while preventing the other to do the same is through access modifier.
If Project.BLL and Project.Model is within the same assembly, you can use the internal modifier to restrict the access from other assembly. or apply a [assembly: InternalsVisibleTo("Project.BLL")] on Project.Model.ModelName
//1. Add a setter on the property, or :
public string Name
{
get { return _name; }
internal set { _name = value; }
}
//2. Add a setter method for _name :
internal void SetName(string value)
{
_name = value;
}

What is the purpose of accessors?

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
Warning: I am assuming you already know about object-oriented programming.
What are properties?
Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.
Why do they exist?
They aim to solve the following problems:
Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.
In Java, you often say:
class person
{
private int _age;
public void setAge(int value) { /*check value first, then set _age*/ }
public int getAge() { return this._age; }
}
and then consistently say:
if (person.getAge() > blah || person.getAge() < 10)
{
person.setAge(5);
}
After a while, the get and set become rather annoying.
Providing direct access to the actual variable breaks encapsulation, so that's not an option.
How are they used?
They are used just like variables. You read/write to them just like variables.
How are they created?
They are created as methods. You define a pair of methods that:
Return the current value of the property. Oftentimes, this is nothing more than something like the following:
class Person
{
private int _age; //Declare the backing field
public int Age
{
get { return this._age; }
set { ... }
}
}
Set the value of the property:
class Person
{
public int Age
{
get { ... }
set
{
if (value < 0) //'value' is what the user provided
{ throw new ArgumentOutOfRangeException(); } //Check validity
this._age = value;
}
}
}
Other notes:
Auto-implemented Properties
C# 3.0 introduced auto-implemented properties:
public int Age { get; set; }
This is equivalent to:
private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }
Why does it exist?
It helps you avoiding breaking changes in client executables.
Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.
What happens?
The depending executable breaks, because the code is no longer valid.
Auto-implemented properties help you avoid that, without extra redundancy in your initial code.
Indexers
Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].
Example:
private int[] _elements;
public int this[int index] //Indexed property
{
get { return this._elements[index]; }
set
{
//Do any checks on the index and value
this._elements[index] = value;
}
}
You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:
var list = new List<int>();
list.Add(10);
list[0] = 5; //You're indexing list, as though it were an array!
Isn't that neat? :)
Anything else?
There are many more features to properties, not all of which are available in C#:
Parametrized properties, of which indexers are a special kind
Getter/setter access modifiers (in C#)
Multiple getters or setters (not in C#)
Et cetera
They are called Accessors
The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.
The body of the get accessor resembles that of a method. It must return a value of the property type.
http://msdn.microsoft.com/en-us/library/w86s7x04.aspx
private string m_Name; // the name field
public string Name // the Name property
{
get
{
return m_Name;
}
}
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.
private m_Name;
public string Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
Then in the incarnation of C# 3, you can do this much easier through auto-properties
public string Name {get; set; } // read and write
public string Name {get; } // read only
public string Name { get; private set; } //read and parent write
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Properties act as accessors to the internal state of an object, hiding the implementation of that state.
So, for example, you may have a first name property in a class
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
}
}
So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
set {set this.firstName = value;}
}
}
Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.
Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.
For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.
Here's what I mean:
public class User {
//Usery properties here, and...
private string _password;
public string Password {
get {
return _password;
}
set {
_password = SomeHashingFunction(value);
}
}
}
value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";
Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.
Example without properties:
private int test;
public int getTest() {
// some computation on test here, maybe?
return test;
}
private void setTest(int test) {
// some error/range checking, maybe?
this.test = test;
}
With properties:
private int test;
public int Test {
get {
// some computation on test here, maybe?
return test;
}
private set {
// some error/range checking, maybe?
test = value; // value is a keyword here
}
}
get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:
public class Foo()
{
//Field
private int _bar;
//Property
public int Bar
{
get { return _bar; }
set { _bar = value; }
//value is an implicit parameter to the set acccessor.
//When you perform an assignment to the property, the value you
//assign is the value in "value"
}
}
In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.
Now in a class that has an instace of Foo, you can do this:
public class IHasAFoo()
{
private Foo _myFoo = new Foo();
public void SomeMethod()
{
_myFoo.Bar = 42;
}
}
So the public accessor allows you to set the value of the private field back in Foo.
Hope that helps!

What does this mean ? public Name {get; set;} [duplicate]

This question already has answers here:
What is the { get; set; } syntax in C#?
(20 answers)
Closed 8 years ago.
I see this quiet often in C# documentation. But what does it do?
public class Car
{
public Name { get; set; }
}
It is shorthand for:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
The compiler generates the member variable. This is called an automatic property.
In simple terms they are referred as property accessors. Their implementation can be explained as below
1.get{ return name}
The code block in the get accessor is executed when the property is Read.
2.set{name = value}
The code block in the set accessor is executed when the property is Assigned a new value.
Eg.(Assuming you are using C#)
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Now when you refer to this property as below
Person p = new Person();// Instantiating the class or creating object
'p' of class 'Person'
System.Console.Write(p.Name); //The get accessor is invoked here
The get accessor is invoked to Read the value of property i.e the compiler tries to read the value of string 'name'.
2.When you Assign a value(using an argument) to the 'Name' property as below
Person p = new Person();
p.Name = "Stack" // the set accessor is invoked here
Console.Writeline(p.Name) //invokes the get accessor
Console.ReadKey(); //Holds the output until a key is pressed
The set accessor Assigns the value 'Stack" to the 'Name property i.e 'Stack' is stored in the string 'name'.
Ouput:
Stack
It's an automatic read-write property. It's a C# 3.0 addition. Something like:
public class Car {
private string name;
public string Name { get { return name; } set { name = value; } }
}
except that you can't directly access the backing field.
It's called an Auto-Implemented Property and is new to C# 3.0. It's a cleaner syntax when your access to the property doesn't need any special behavior or validation. It's similar in function to:
public class Car
{
private string _name;
public string Name
{
get { return _name; }
set {_name = value; }
}
}
So it saves a fair amount of code, but leaves you the option later to modify the accessor logic if behavior or rules need to change.
It is the equivilent of doing:
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; }
}
Except you don't have access to the private variable while inside the class.
Auto-Implemented Properties
SUMMARY:In C# 3.0 and later, auto-implemented properties make
property-declaration more concise when
no additional logic is required in the
property accessors.

Passing a property as an 'out' parameter in C#

Suppose I have:
public class Bob
{
public int Value { get; set; }
}
I want to pass the Value member as an out parameter like
Int32.TryParse("123", out bob.Value);
but I get a compilation error, "'out' argument is not classified as a variable." Is there any way to achieve this, or am I going to have to extract a variable, à la:
int value;
Int32.TryParse("123", out value);
bob.Value = value;
You'd have to explicitly use a field and "normal" property instead of an auto-implemented property:
public class Bob
{
private int value;
public int Value
{
get { return value; }
set { this.value = value; }
}
}
Then you can pass the field as an out parameter:
Int32.TryParse("123", out bob.value);
But of course, that will only work within the same class, as the field is private (and should be!).
Properties just don't let you do this. Even in VB where you can pass a property by reference or use it as an out parameter, there's basically an extra temporary variable.
If you didn't care about the return value of TryParse, you could always write your own helper method:
static int ParseOrDefault(string text)
{
int tmp;
int.TryParse(text, out tmp);
return tmp;
}
Then use:
bob.Value = Int32Helper.ParseOrDefault("123");
That way you can use a single temporary variable even if you need to do this in multiple places.
You can achieve that, but not with a property.
public class Bob {
public int Value { get; set; } // This is a property
public int AnotherValue; // This is a field
}
You cannot use out on Value, but you can on AnotherValue.
This will work
Int32.TryParse("123", out bob.AnotherValue);
But, common guidelines tells you not to make a class field public. So you should use the temporary variable approach.

Categories

Resources