Boolean properties in c# - c#

This might be a dumb question, but the property below, will there ever be a situation where just getting it will cause an exception?
Like if I did something like bool value = this.BatchValuation; - but I hadn't set BatchValuation yet, will it just set value to null, or will it cause an exception?
public bool BatchValuation { get; set; }

This might be a dumb question
It is not.
in the property below, will there ever be a situation where just getting it will cause an exception?
Possibly, yes. For example, another thread could abort your thread while it was in the middle of fetching that property; that would appear to be an exception thrown by the property getter. Or, you could run out of stack space right at the moment where the property is called, and an out-of-stack exception could be thrown. Or, when you call the property for the first time, the jitter might start up and try to allocate virtual memory for the generated code, but you are all out of virtual address space, so an out of memory exception could be thrown.
Those are all extraordinarily unlikely, but they are all possible. You asked if there would ever be such a situation, not if it was likely.
If I hadn't set BatchValuation yet, will it just set value to null, or will it cause an exception?
Neither; it will default to false. Booleans are not nullable.

boolean values default to false if you have not set them specifically. So no there will be no exception, the property will just return false.
Remember that this is a value type we are talking about, only variables for reference types can be set to null. Value types do have a default value, which is zero for numeric types and false for boolean.
Also see Default Values Table

no, Boolean defaults to false. So
bool something; // something is false

In the context of class properties or member fields, each field is initialized to a default value for the type when the class is created prior to the constructor being run. In the class
class Foo
{
bool bar;
string s;
int item;
public double Baz { get; set; }
}
The first three fields are set to their initial values (false, null, and 0, respectively), and the auto-generated backing field for Baz is also set to 0.0d. It is not an error to access these fields/properties without explicit user-initialization, unlike accessing uninitialized locals. It is for locals that the compiler requires explicit initialization.
class Foo
{
int bar;
void M()
{
Console.WriteLine(bar); // not an error, bar is 0;
bool someBool;
Console.WriteLine(someBool); // use of uninitialized local variable
}
}

As BrokenGlass said, the boolean values default to false,
you can test it by yourself, I provide a sample as below.
static void Main()
{
// Create an object, but don't set attribute.
Foo foo = new Foo();
if (!foo.BatchValuation)
Console.WriteLine("BatchValuation is False");
else
Console.WriteLine("BatchValuation is True");
Console.ReadKey();
}
}
// Test class.
public class Foo
{
private bool _batchValuation;
public Foo() { }
public bool BatchValuation
{
get { return _batchValuation; }
set { _batchValuation = value; }
}
}

Once I had a very weird situation, when auto-implemented property like this threw a NullReferenceException exception. The reason was Emit Mappper library (http://emitmapper.codeplex.com/).
This library (which is very good otherwise) uses Refleciton.Emit and, when it sees no public constructor for the type, it emits mapping call sites, which pass null reference as implied first argument of property/method (which ends up as "this" in all instance methods).
So the property was trying to change field value of a null reference (that is, I had this==null situation)!

Related

C# define that a class instance can never be null (it only contains no data)

Out of curiosity: Is there a way to create a class whose reference to the class instance can never be set to null?
Like haveing only a readonly pointer that can only be set to null by the class itself.
What I have in mind:
I would want to have an easy to read /use object that either exists with data or exists without (shown by an attribute like hasData = false). It is always accessable and should never be null / point to nowhere which as a side effect gets also rid of NullReferenceExceptions for objects that are sometimes supposed to not have a value without the need of checking for null.
This feature does not exists (yet). There is big discussion of non-nullable reference types at Roslyn forum: non-nullable reference types (the one billion $ mistake). But currently you cannot restrict reference type variable from assigning null value.
You can use value type (struct) instead, but it's not stored in heap, passed by value etc.
All other options will not guarantee that someone will not assign null to variable of your reference type. But you still can use something like Null Object pattern to simplify your life (processing objects without data in same way as usual objects).
In such a case, you may want to use a struct instead of a class. Class is a reference type and therefore its default value is null, hence a variable containing an instance can be nulled (assigned null). There is no way to prevent it. On the other hand, struct is a value type and default for struct is an empty struct - i.e. a struct whose members are set to their defaults (0 for an int field, null for a field of a reference type etc.)
Example of a struct
public struct Foo
{
public int Bar;
}
And its usage (notice it is not instantiated but still it is NOT null)
Foo foo;
foo.Bar = 1;
More about structs can be found here on the MSDN sites.
As Anton mentioned, you could use a struct which cannot have a default value of null. But I am thinking you want something more like this:
public class DataObject
{
public static bool HasData
{
get
{
return myObject != null;
}
}
public static DataObject PresistentDataObject
{
get
{
return myObject;
}
}
static DataObject myObject = new DataObject();
}
This code seems like bad practice. And maybe you'd want to resort to something like dependency injection with a singleton which will avoid setting up a state class like this.
Typically, the motivation behind such a question drives the qualities/properties of a solution.
Here, I suppose, the motivation is to avoid runtime exceptions of (faulty) code which tries to access a null reference as if it held an instance.
class Foo<T> {
T data; // might be null or hold an instance...
Foo<T>() {
data = GetInstanceOfTInMysteriousWays(); // might return null...
}
bool DoSomething() {
return data.Value > 5; // might throw an exception...
}
// ... more members...
}
To prevent this type of errors, you could borrow from C#'s cousin language F#.
If the function T GetInstanceOfTInMysteriousWays<T>() by design and contract is permitted to either return an instance or a null value, a better design of that function would be to have it return not T but an Option<T>. Then, the type of Foo.data would not be T but Option<T> and the user code in DoSomething() could not simply access member data.Value. Thus, this common pattern of bugs would be eliminated.
// Improved code from above
class Foo<T> {
Option<T> data; // Option is a struct type and cannot be null...
Foo<T>() {
data = GetInstanceOfTInMysteriousWays();
}
bool DoSomething() {
if (data.IsSome() ) {
return data.TryGetValue().Value > 5;
}
return false;
}
}
Now the only question is, where to find that Option type in C#? There are several github projects creating such a type (google is your friend). You could also consider to link the F# core library and use the Option type defined there, maybe along with a little helper as is shown in this gist snippet.
If your class is named foo, then you would have at least one constructor (possibly more). In that constructor you would assign the variable to false.
public foo(){
hasData = false;
}
As #Anton points out, this only works if the variable is instansiated.
foo f = new foo();
it would still be null if you assigned it as null:
foo f = null;
I'm not sure, I understand the question correctly or not. Let me add
some points here:
Hope that you misunderstand the term Instance, If you create an instance of the class then it will not be null, Let myClass be a class that you have created already. You are not creating any instance of the class by using myClass myClassObject. The myClassObject will became an instance of the class only when an instance of the class is assigned to it, Until then it is null which means not existing.
As others have mentioned, you'd need a struct for that.
However, we can tackle this from a different angle (in a class):
Since the variable can point to null, let's define the variable in a way that it can't be set to null:
private Class1 _c = new Class1();
public Class1 c { get { return _c; } set { if (value != null) _c = value; } }
so c will not be set to null.
A struct per your requirements:
struct Struct1
{
public bool hasData { get { return Data != null; } }
public Class1 Data;
}

Pass by reference and storing a reference to a variable - c#

Am I misunderstanding something about pass by reference?
SomeClass is the IObserver implementer:
bool value = false;
provider.Subscribe(new SomeClass(ref value));
while (!value)
{
provider.GetEvents() //triggers OnNext
}
In SomeClass:
public SomeClass(ref bool value)
{
this.value = value;
}
public void OnNext(object someUpdatedValue)
{
value = true;
}
Value never becomes true and the while loop never breaks. How come? Does assigning the value property of SomeClass to the reference of value not persist?
Edit: After seeing the first two responses my new question is this:
How can I achieve this kind of behavior without using static variables?
Pass by reference affects only the variable passed as the argument to the method. In your example, the value of false, which is what the variable value contained when you assigned it to this.value, is copied to the this.value field. Nothing more.
There's nothing magical in C# that will remember where that value came from and update the variable later, when the field to which its value was assigned is changed later.
Does assigning the value property of SomeClass to the reference of value not persist?
You aren't assigning "the reference of value". All that happens when you pass by-reference is that if the local variable itself is changed, then the variable that was passed is modified. When you use the value of the variable, you're only using the value, not the reference.
EDIT:
Without more context, it's impossible to say what the best way to approach this would be. But note that reference types achieve something similar to what you seem to be trying to do. For example:
class VolatileBoolWrapper
{
public bool Value { get { return _value; } }
private volatile bool _value;
public void SetValue(bool value)
{
_value = value;
}
}
VolatileBoolWrapper value = new VolatileBoolWrapper();
provider.Subscribe(new SomeClass(value));
while (!value.Value)
{
provider.GetEvents() //triggers OnNext
}
public SomeClass(VolatileBoolWrapper value)
{
this.value = value;
}
public void OnNext(object someUpdatedValue)
{
value.SetValue(true);
}
In that way, the VolatileBoolWrapper class acts as a go-between for the caller and callee.
<edit>
Note that I marked the field as volatile, and named the class Volatile... just to be safe. There's not enough context in the question for me to know what "triggers" actually means (i.e. does the same thread actually set the value, or is this something that involves interaction between threads).
If it happens that the call to OnNext() occurs within the same thread, strictly by virtue of the call to GetEvents(), then you can omit the use of volatile here (and ignore, or at least discount, my note about polling below).
</edit>
All that said, frankly: polling on a variable like this is pretty much always the wrong way to accomplish one's goals. There have always been much better approaches for things like this, but in modern C#, I would say that TaskCompletionSource is the best alternative. Like other mechanisms that came before it, it allows your waiting code to not continually use CPU time checking to see if the event has occurred; unlike them, it also provides an excellent mechanism for allowing that entire thread to continue executing, performing other work, only resuming at the await statement where you waited for the event when that event actually occurs.
The ref modifier affects the caller, not the callee. It allows you to reassign the caller's variable to "point to" a new value. For example:
bool myValue = true;
WithoutRef_YouCannotReassign(myValue);
Console.WriteLine(myValue); // myValue is still true
WithRef_YouCanReassign(ref myValue);
Console.WriteLine(myValue); // myValue is now false
void WithoutRef_YouCannotReassign(bool value) {
value = false;
}
void WithRef_YouCanReassign(bool value) {
value = false;
}
You're trying to pass out a reference to SomeClass.value. Normally, that'd work great by just swapping your assignment (remember, you're changing the caller's variable to point at something else)
public SomeClass(ref bool value)
{
value = this.value;
}
But, you've got another problem. Since a bool is immutable - even though your caller is pointing at the right value, you point your own value to something else later by overwriting it:
public void OnNext(object someUpdatedValue)
{
value = true; // value is now pointing somewhere else! the caller never got a reference to the somewhere else!
}
So, now, you actually need a wrapper to avoid having to overwrite SomeClass.value after you passed a reference out to it:
struct MyBoolWrapper
{
public bool Value { get; set; }
}
public SomeClass(ref MyBoolWrapper value)
{
value = this.value;
}
public void OnNext(object someUpdatedValue)
{
value.Value = true;
}
Now, this won't work because it's a struct (like bool is). structs are value types, and so the value of it gets copied back. When you change SomeClass.value, you're changing a different copy again! (This is one reason we tend to prefer immutable structs, like bool is).
So, let's change this to a class:
class MyBoolWrapper
{
public bool Value { get; set; }
}
This will work as expected since you end up passing back a reference to MyBoolWrapper (which doesn't change).
So, now we're working - but let's look at some cleanup. It seems a little silly for our caller to have to new a MyBoolWrapper just so that we can point it to something else. Let's change that:
MyBoolWrapper wrapper = null;
provider.Subscribe(new SomeClass(ref wrapper));
Well, now it seems silly that we set it to null. Since SomeClass is providing all the info, let's just make it an out (which, essentially, works the same as ref just without requiring it to be initialized):
MyBoolWrapper wrapper;;
provider.Subscribe(new SomeClass(out wrapper));
Of course, now it's not even clear why we can't just hold a reference to SomeClass directly, and get rid of this whole out/ref dance:
SomeClass someClass = new SomeClass();
provider.Subscribe(someClass);
while (!someClass.Value) {
provider.GetEvents();
}
class SomeClass {
public Value { get; private set; }
public void OnNext(object someUpdatedValue)
{
Value = true;
}
}
There - that's simpler. Since the caller has a reference to our instance that changes it's state (without changing it's identity), we don't have to worry about all of that method calling by-ref/by-val struct vs class mumbo-jumbo.

Is property a container and accessor in C#?

I have this property in my Class:
public string A
{
set
{
A = value;
}
}
It gives me an error whenever I try to assign a value to A. Actually, my IIS Express stops and gives no clue.
I have a feeling that this creates an endless assignment of value to A, it's like a recursion. My questions:
What is happening in my code?
Is property just an accessor (getter/setter) and not a container when you specify an implementation?
When using auto-implemented property, is the property both container and accessor?
You'll have a StackOverflow exception, since you're assigning the property itself in its setter, which results in an endless assignment.
You can not set property variable itself as a container..
you can write like this.
Scenario 1:
public string A
{
set;
}
Scenario 2:
private string _A=String.Empty;
public string A
{
set{_A=value;}
}
let me know if any question.
When you are using an auto implemented property, the compiler generates a container for the value and methods to work with that container (get and set).
When you implement the propriety yourself, like you did, the compiler only generates a set method, that then calls itself, resulting in an endless loop. The correct way to do it would be:
private string _a;
public string A
{
set
{
_a = value;
}
}
In this case, the compiler will generate a method to set the value of _a , and no recursion occurs.

c# initializing

is it necessary to initialize an auto property?
public string thingy { get; set; }
the reason I ask is because I have just come across a bunch of code where it was used where, the default value of null being an acceptable value.
the compiler does not complain.
as a general point, why does the compiler enforce initializations if it will default numbers to zero and object references to null anyway?
autopropeties initialize by default(T) if you want initialize by special value you can use backing field:
private string _thingy = "value";
public string Thingy
{
get { return _thingy; }
set { _thingy = value; }
}
or set value in constructor
public class MyClass
{
public string Thingy{get;set;}
public MyClass()
{
Thingy = "value";
}
}
or set in any method
The compiler enforces initializations for local variables, not for fields or properties. C# requires that local variables be definitely assigned because use of unassigned local variables is a common source of program bugs. That's not because the unassigned variable might contain garbage -- the CLR guarantees that it will not -- but because the programmer has probably made a mistake in the code.
The compiler doesn't treat fields or properties the same way because it's impossible to do the necessary flow analysis across multiple methods that could be called in any order.

How to have a C# readonly feature but not limited to constructor?

The C# "readonly" keyword is a modifier that when a field declaration includes it, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors, a lazy/late evaluation/initialization maybe.
How could I do that? and is it possible to do it in a nice way, for example, is it possible to write some attribute to describe this?
If I understand your question correctly, it sounds like you just want to set a field's value once (the first time), and not allow it to be set after that. If that is so, then all the previous posts about using Lazy (and related) may be useful. But if you don't want to use those suggestions, perhaps you can do something like this:
public class SetOnce<T>
{
private T mySetOnceField;
private bool isSet;
// used to determine if the value for
// this SetOnce object has already been set.
public bool IsSet
{
get { return isSet; }
}
// return true if this is the initial set,
// return false if this is after the initial set.
// alternatively, you could make it be a void method
// which would throw an exception upon any invocation after the first.
public bool SetValue(T value)
{
// or you can make thread-safe with a lock..
if (IsSet)
{
return false; // or throw exception.
}
else
{
mySetOnceField = value;
return isSet = true;
}
}
public T GetValue()
{
// returns default value of T if not set.
// Or, check if not IsSet, throw exception.
return mySetOnceField;
}
} // end SetOnce
public class MyClass
{
private SetOnce<int> myReadonlyField = new SetOnce<int>();
public void DoSomething(int number)
{
// say this is where u want to FIRST set ur 'field'...
// u could check if it's been set before by it's return value (or catching the exception).
if (myReadOnlyField.SetValue(number))
{
// we just now initialized it for the first time...
// u could use the value: int myNumber = myReadOnlyField.GetValue();
}
else
{
// field has already been set before...
}
} // end DoSomething
} // end MyClass
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors
Note that lazy initialization is complicated, so for all of these answers you should be careful if you have multiple threads trying to access your object.
If you want to do this inside the class
You can use the C# 4.0 built-in lazy initialization features:
http://msdn.microsoft.com/en-us/library/dd997286.aspx
http://msdn.microsoft.com/en-us/library/dd642331.aspx
http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/
Or for older versions of C#, just supply a get method, and check if you're already initialized by using a backing field:
public string SomeValue
{
get
{
// Note: Not thread safe...
if(someValue == null)
{
someValue = InitializeSomeValue(); // Todo: Implement
}
return someValue;
}
}
If you want to do this outside the class
You want Popsicle Immutability:
http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx
http://msdn.microsoft.com/en-us/library/ms750509.aspx
http://csharpindepth.com/Talks.aspx (search for "popsicle immutability" and you'll find a video)
Basically:
You make the whole class writable, but add a Freeze method.
Once this freeze method is called, if users try to call setters or mutator methods on your class, you throw a ModifyFrozenObjectException.
You probably want a way for external classes to determine if your class IsFrozen.
BTW, I made up these names just now. My selections are admittedly poor, but there is no generically followed convention for this yet.
For now I'd recommend you create an IFreezable interface, and possibly related exceptions, so you don't have to depend on the WPF implementation. Something like:
public interface IFreezable
{
void Freeze();
bool IsFrozen { get; }
}
You can use the Lazy<T> class:
private readonly Lazy<Foo> _foo = new Lazy<Foo>(GetFoo);
public Foo Foo
{
get { return _foo.Value; }
}
private static Foo GetFoo()
{
// somehow create a Foo...
}
GetFoo will only be called the first time you call the Foo property.
This is know as the "once" feature in Eiffel. It is a major oversight in C#. The new Lazy type is a poor substitute since it is not interchangeable with its non-lazy version but instead requires you to access the contained value through its Value property. Consequently, I rarely use it. Noise is one of the biggest problems with C# code. Ideally, one wants something like this...
public once Type PropertyName { get { /* generate and return value */ } }
as oppose to the current best practice...
Type _PropertyName; //where type is a class or nullable structure
public Type PropertyName
{
get
{
if (_PropertyName == null)
_PropertyName = /* generate and return value */
return _PropertyName
}
}

Categories

Resources