C# struct non-static struct member cannot have initializer [duplicate] - c#

This question already has answers here:
Why can't I initialize my fields in my structs?
(4 answers)
Closed 8 years ago.
What is the cause of the error on the screen?
public struct YetkiYapisiListesi
{
public bool STOKGUNCELLE =false ;
public bool STOKSIL=false;
public bool STOKLISTELE=false;
}
Non-static struct member cannot have initializer

C# does not allow structs to have initializers, the reason why has been debated before, see here: ( Why can't I initialize my fields in my structs? )
Simply remove the = false part from your field declarations.
Note that Boolean fields are false by default, making your assignment completely unnecessary.
If you absolutely need fields to have initialized to non-default values then you can still define an additional constructor that sets those values, however it cannot be the default (parameterless) constructor. One alternative option then, is to use a static factory method.

You can't initialize field on Struct.
You will get the same result even if you ommit initializing :
public bool STOKGUNCELLE;
public bool STOKSIL;
public bool STOKLISTELE;
public bool STOKHAREKET;
Because bool default value are false .

Related

Initialization order of static readonly field [duplicate]

This question already has answers here:
Order of static constructors/initializers in C#
(4 answers)
Closed 8 years ago.
I'm curious of the C# spec says anything about the order of initializing static field's in C# 5 (.net4). For instance:
public class Test
{
public static readonly string A = "hi";
public static readonly string B = "bye";
public static readonly string DEFAULT = A;
}
In testing (Mono 2.x) they seem to be initialized in the order they appear in code. eg. As is, DEFAULT will have the value "hi", but if I move the definition for DEFAULT above A and B, it will be assigned NULL because A hasn't been assigned yet.
Is there a guarantee that the variables are initialized in order? Or is it up to the compiler?
Thanks.
It is in the order that they appear in. See here.
The static field variable initializers of a class correspond to a
sequence of assignments that are executed in the textual order in
which they appear in the class declaration.
Also, when you have a static constructor:
If a static constructor (Section 10.11) exists in the class,
execution of the static field initializers occurs immediately prior to
executing that static constructor. Otherwise, the static field
initializers are executed at an implementation-dependent time prior to
the first use of a static field of that class.

Properties with or without private fields [duplicate]

This question already has answers here:
Any reason to use auto-implemented properties over manual implemented properties?
(7 answers)
Closed 9 years ago.
What is more "true": use properties with or without private fields.
I.e.
1.
class A
{
int _field;
public int Field
{
get{ return _field;}
set{_field = value;}
}
}
2.
class A
{
public int Field{get;private set;}
}
Number 2 creates a backing field automatically, so you always have a private field "behind the scenes" (although not directly accessible in the latter case).
when you create anonymous property compiler creates corresponding field for you, so it's pretty much the same, but you can access autocreated field only via property
It makes no difference - the compiler generates the property implementation for you in exactly the same way that it generates a default constructor or the code for a using statement. These two classes are nearly 100% equivalent which you can see if you decompile an auto-property (the only difference is the name of the generated backing field that the compiler uses)
class A
{
public int Field {get; private set;}
}
class A
{
int _field;
public int Field
{
get { return _field; }
private set {_field = value; }
}
}
Its completely down to your personal preference.
As has already been stated, the second creates the backing field at compile time. You would typically define a backing field your self if you wanted the property to act as a public accessor to the field, where you can add custom logic or prevent the value being modified (using the private keyword on the setter).

Unable to compile a struct [duplicate]

This question already has answers here:
Struct constructor: "fields must be fully assigned before control is returned to the caller."
(5 answers)
Auto-properties and structs
(3 answers)
Closed 9 years ago.
The following code suggests I cannot use implicit properties with a struct:
public struct LimitfailureRecord
{
public LimitfailureRecord(string sampleCode)
{
SampleCode = sampleCode;
}
public string SampleCode {get; set;}
{
}
}
It fails to compile, with the error message
"Backing field for automatically implemented property
'blahblah.LimitfailureRecord.SampleCode'
must be fully assigned before control is returned to the caller.
Consider calling the default constructor from a constructor
initializer."
If I change the struct to a class it's fine.
What do I need to do to make this work as a struct? I'd rather not go to the lengths of backing fields (this is a heavily stripped down version of the real code) if I can avoid it.
With structs you have to call the default constructor in all other constructors:
public LimitfailureRecord(string sampleCode) : this()
{
SampleCode = sampleCode;
}
Use a constructor chaining like so:
public LimitfailureRecord(string sampleCode)
: this()
{
...
}
The reason is the auto-implemented property introduces a (generated) instance field for backing, as described. All instance fields must be assigned to in an instance constructor of a struct.
Actually the error text you quote describes the fix pretty well.
Something else: If you keep the set accessor of your property public you will have a mutable struct. Most people agree that mutable structs should be avoided and are "evil" because their copy-by-value semantics and the possibility of mutating an existing struct value (as in record.SampleCode = "Here's a new string for an old object";) don't go well together. Check the threads on mutable and immutable structs.
You either need to call the default constructor or change the method name.
So;
public struct LimitfailureRecord
{
public void init(string sampleCode)
{
SampleCode = sampleCode;
}
public string SampleCode { get; set; }
}
Will work or just make the method definition; LimitfailureRecord(string sampleCode) : this()
The later is better because it only requires one call to make things work. If you go the init route you have do do new LimiFfailureRecord then call init after. structs in C# simply require you to call the default constructor, this isn't the case with classes which is why it will compile if you change it to a class.

Honestly, what's the difference between public variable and public property accessor? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
What is the difference between:
public string varA;
and
public string varA { get; set; }
The public property accessor gives you more flexibility in the future.
If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.
There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.
In addition to the other answers, you can also use a property to make the value read-only or even set-only:
public int Item { get; private set; } // read-only outside the class. Can only be set privately.
I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.
Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.
Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).
When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:
private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}
In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

C# Struct Generic Constructor [duplicate]

This question already has answers here:
How can I set the value of auto property backing fields in a struct constructor?
(2 answers)
Closed 9 years ago.
Using this code:
struct Foo<T1>
{
public T1 Item1 { get; private set; }
public Foo(T1 item1)
{
Item1 = item1;
}
}
I encounter this error:
Backing field for automatically implemented property 'Foo.Item1' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
My question is, why is the property Item1 not fully assigned after the constructor is called?
Edit: Changed set to private set because this question has nothing to do with mutability.
Add this() in here:
public Foo(T1 item1) : this()
{
Item1 = item1;
}
It's because you're assigning to a property, and the compiler can't deduce that the property only assigns a value to a variable; it could do other things before the instance is initialized, and that's not allowed because the structure might have garbage data. So you have to initialize it with the default constructor first, then do what you want.

Categories

Resources