I'd like to take simple public properties and turn them into anonymous accessors, but some of my logic requires the initial values of the accessors/properties be null, can I rely on anonymous accessors to be null if I've not assign them a value?
currently :
public string XML = null; // set XML or XMLPath to turn on XML stuff
public string XMLPath = null;
compared to :
public string XML {get; set;}
public string XMLPath {get; set;}
You don't need to do anything. They are null by default. This is true also for fields. Actually, a automatic property also uses a field and that's why the default value of an automatic property is null (or default(T) to be more precise).
Unassigned auto-implemented properties are defined to start with the default value for their type. So reference types start null.
New class fields are always initialized with nulls (except simple types which are initialized with them default values, like 0 for integer). You do not need to assign the null to them. It all aplies to auto implemented properties and fields in anonymouse object too.
Only method variables are not initialized, but as for them if you'll try to read them without initializing them first you'll get the compiler error first, so you don't need to worry here either.
Conclusion: C# always cares about not accessing uninitialized variables on compile-time, there is no chance that you will access variable that do not have default value assigned on runtime.
Related
In c# using .Net, if you create a class with an uninitialized field and without a constructor, then create an instance of the class with the new keyword, .Net sets the value of the field to the "default value". What exactly does that mean? Is there ever a situation where the value would be set to Null?
Like Johnny mentioned in the comments, this table lists the default values for .NET types. The default value of a reference-type field is null.
The default value is defined on a per-type basis. In general, any reference type will default to null.
You can find a full list of default values based on the type in the documentation.
Furthermore, you can find out empirically by explicitly using the default keyword and checking (e.g. in the debugger) what value was returned:
var x = default(string);
var y = default(int);
I have a basic test console app going with the following property:
public static string testString { get{ } set{ } }
I want to do a sort of singleton like setup with the property where if the property value is null, I initialize the property and return the property value. If it's not null, I return the current property value.
Bad practices aside, is this possible without using an additional variable?
Trying to check the value of the property within get{} using traditional means of course creates a stackoverflow exception. I presume each time it tries to check null it's just using the getter again and getting stuck in an infinite loop.
Properties are just syntax sugar for getter/setter methods. So there is no in-build storage behind them.
Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Therefore you have to create a field or so.
(There are also auto-implemented properties, for which which the compiler creates backer fields automatically. But you do not have direct access to these fields anyway.)
Yes this is quite possible:
private static string _testString;
public static string testString {
get
{
return _testString = _testString ?? "MyDefaultValue";
}
set
{
_testString = value;
}
}
Adding a private field will do what you're wanting. While this may look like an additional variable, this is what actually occurs when your application gets compiled. No loss of optimization or performance.
If you use an initializer list to create a struct, do the members you leave out get a known default value?
public struct Testing
{
public int i;
public double d;
public string s;
}
Testing test = new Testing { s="hello" };
I found a link at Microsoft that implies it but does not state so explicitly: Default Values Table (C# Reference).
A small test program shows that it does not generate a compiler error and produces the expected results. I know better than to rely on simple tests for guarantees though. http://ideone.com/nqFBIZ
Yes, they contain default(T) where T is the type of the value.
Object references will be null.
Excerpt:
As described in Section 5.2, several kinds of variables are
automatically initialized to their default value when they are
created. For variables of class types and other reference types, this
default value is null. However, since structs are value types that
cannot be null, the default value of a struct is the value produced by
setting all value type fields to their default value and all reference
type fields to null.
Taken from here:
http://msdn.microsoft.com/en-us/library/aa664475(v=vs.71).aspx
I remember when studying the MOC for the certification that they explicitly state this. It is a guaranteed feature of the language.
To expand on pid's answer:
test = new Testing { s = hello }
is specified as having the semantics of:
Testing temp = new Testing();
temp.s = "hello";
test = temp;
The default constructor of a value type is documented as the constructor which sets all the fields of the instance to their default values.
More generally, the C# language requires that any constructor of a value type have the property that all fields be definitely assigned before the constructor terminates normally.
Now, if no constructor is called then there are two cases. If the variable is initially assigned then the variable acts the same as though the default constructor was called. For example, if you say
Testing[] test = new Testing[1];
Then test[0] is initialized to the default value the same as if you'd said
Testing[] test = new Testing[1] { new Testing() };
If the variable is not initially assigned, for example, a local variable, then you are required to definitely assign all the fields before you read them. That is, if we have a local:
Testing test;
test.s = "hello";
Console.WriteLine(test.d); // ERROR, test.d has not been written yet.
Note also that mutable structs are a worst practice in C#. Instead, make a public constructor that sets all the fields, make the fields private, and put property getters on top of them.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between Property and Field in C#
I know it is a very basic question but I cannot read any valid answer after searching
E.g
public string abc;
public string abc { get; set; }
Please describe this.
(About my terminology: "field" = public variable, "property" = get/set)
One thing to be mentioned additionally to the differences in usage: A property, unlike a field, gets compiled to a method (I think it's called something like get_abc internally). Declaring an auto property from beginning on has therefor two advantages:
1) No problems with reflection. If some reflection code is based on the value being a field, and later you think "well, now I'd like to add null testing" and change to a property, then the reflection code will eventally fail (unless you expected that in the reflection, but that would be extra effort for nothing imho)
2) "Warning" of possible side effects. Fields can only change their values, methods can do arbitrary things to a class. So, declaring a property from beginning on signalizes the possibility of other changes happening in the background. (Of course one shouldn't do weird stuff in a setter, but sometimes it isn't impractical to get additional initialization from one value provided; e.g. measuring the length of a list)
I also would say that it's good style to use properties wherever possible. Especially for the two reasons provided, but also for consistency.
Variables store direct value but property are a window to your class and its variables.
Even though they work the same(almost), one very good thing with field is that if you want to do some extra work with field (like validation or doing any calculations) you can do so.
This will explain you
public string _abc;
public string abc
{
get
{
return _abc;
};
set
{
if (value == null)
_abc = "";
else
_abc = value;
};
}
Here if null is passed to property abc then it will be checked it and an empty value will be assigned to _abc. otherwise value.
If we wanted this with a variable. every where we had to do this.
if(foo == null) // here foo is some string
_abc = ""
else
_abc = foo;
with property this can be done like
abc = foo;
Now it will check for in the set section of property.
Properties can contain some code on setting/getting the value. Public variables can't and will not contain any code when you access them. This is a huge difference.
Using a property you're saying to whomever uses you're code that there might be some code behind the value now or in the future.
Using a public variable you're saying its just a boring old field that will contain some value.
One reason for using an auto property instead of a Field is compatibility.
For example, when you assign a field, the CLR does just that. It sets the field.
When you have a property (auto or not), and you type
someObject.Whatever = "Value";
it looks like you are assigning a field, but in reality, the C# compiler inserts something like this for you:
someObject.set_Whatever("Value");
That's not the same as setting a field. And if you have a field and change it to a property later (e.g. if you want to implement change notifications or things like that), you will have to recompile all assemblies that used the original field, since assigning a Field requires different code than setting a property (no matter if auto or not).
There is almost never a reason to use a public field. Automatic properties can be inlined at runtime, so there would be no performance difference. And they leave the possibility open to add additional logic to your get / set methods without having to recompile dependent assemblies.
Same difference as a property over public variable such as property support binding but variable not.
I have a property like this:
public Tuple<String, String>[] Breadcrumbs { get; set; }
and I have a test in one of my methods like this:
if (Breadcrumbs != null && Breadcrumbs.Length > 0) { }
Depending on when this method is called, Breadcrumbs may not have been set. In one test, Breadcrumbs == null evaulates to true.
Will unset properties always have a value? (Will it always be null?)
An automatically-implemented property which hasn't been explicitly set by any code will always have the default value for the property type - which is null for reference types. (For int it would be 0, for char it would be '\0' etc).
An automatically implemented property like this is just equivalent to:
private PropertyType property;
public PropertyType Property
{
get { return property; }
set { property = value; }
}
... except that the backing variable has an unspeakable name (you can't refer to it in code) so it will always start off with the default value for the type.
Auto-properties use backing fields and are compiled to regular properties.
If the Property-Type is a reference type the value would be null, if not the value would be the default value.
Class member variables (called fields), and thus backing variables of properties, are always initialized to their default value, if they are not initialized explicitly, which is null for reference types. The default value for all types is the value whose binary representation consists of all bits set to 0.
On the other hand, C# requires you to initialize local variables explicitly. These are: variables declared in methods, constructors and property accessors and out method parameters; i.e. they are treated as undefined until you assign them a value.
It's logically impossible for it not to have a value. It's going to have to return something, some bunch of 1s and 0s that is at least believed to be a reference to a Tuple<String, String>[], so to that extent it has a value.
It's also the case that all fields in classes get set to their default value (default(T) for whatever type T they are, which is null for all reference types). Otherwise it would be possible to have an object that was in a state that not only didn't make any sense in terms of what it does, but which didn't make any sense by the rules of what .NET expects objects to do. This includes the hidden fields behind automatic properties.
Now, in some languages we can do the equivalent of this:
public Tuple<String, String>[] Breadcrumbs
{
get
{
Tuple<String, String>[] whatIWillSend;
return whatIWillSend;
}
}
If this were allowed, whatIWillSend would have a value defined not by any concious decision on your part, but by what happened to be in memory at the time. It could be null, it could be a valid Tuple<String, String>[] by sheer coincidence (but not the one you wanted to use!), it could be a Dictionary<int, List<string>> that the runtime is now going to think is actually a Tuple<String, String>[] (there goes the type-safety of the entire system), it could be a quarter of a decimal structure. (In the languages that allow such things, it could also be a well-known value that debuggers for such languages set in these cases precisely so to help find bugs caused by it).
That's the closest thing we can get to a property not having a value. Note though that:
It would still have a value, just not a meaningful value.
We aren't allowed to do this in C# anyway.