Why is AppDomainSetup.ShadowCopyFiles a string? - c#

From the documentation:
A String containing the string value "true" to indicate that shadow copying is turned on; or "false" to indicate that shadow copying is turned off.
And its been this way since 1.1. Can anyone shed any light?
I reflector'd the getter and setter for good measure:
public string ShadowCopyFiles
{
get
{
return this.Value[8];
}
set
{
if ((value != null) && (string.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0))
{
this.Value[8] = value;
}
else
{
this.Value[8] = null;
}
}
}
//The referenced Value property...
internal string[] Value
{
get
{
if (this._Entries == null)
{
this._Entries = new string[0x10];
}
return this._Entries;
}
}
private string[] _Entries;
So maybe the Value array begets an easier copy constructor or something?

Lack of caffeine. Some things are not meant to be understood.
This clearly seems to be a mistake from .NET first version, not fixed because that could break "legacy" code.
Gosh, I just found this:
Thanks for your feedback on the .NET Framework! We agree that this is an oversight and that the property type should be a boolean. However, it is quite difficult (if not impossible) to make this change in a backwards compatible release (such as Orcas), because we would break the code of any customer relying on string comparisons. So unfortunately we must weigh the risk of breaking compatibility vs. the benefits of API cleanliness...and when it comes to best supporting our customer base, the former typically wins. We will track this internally as a good thing to improve and we'll continue to consider it in future releases.
From here

Related

c# which is the better way to declare two parameters

I have a very quick question about the best way to use two variables. Essentially I have an enum and an int, the value for which I want to get within several ifs. Should I declare them outside the if's or inside - consider the following examples:
e.g.a:
public void test() {
EnumName? value = null;
int distance = 0;
if(anotherValue == something) {
distance = 10;
value = getValue(distance);
}
else if(anotherValue == somethingElse) {
distance = 20;
value = getValue(distance);
}
if (value == theValueWeWant){
//Do something
}
OR
e.g.2
public void test() {
if(anotherValue == something) {
int distance = 10;
EnumType value = getValue(distance);
if (value == theValueWeWant){
//Do something
}
else if(anotherValue == somethingElse) {
int distance = 20;
EnumType value = getValue(distance);
if (value == theValueWeWant){
//Do something
}
}
I am just curious which is best? or if there is a better way?
Purely in terms of maintenance, the first code block is better as it does not duplicate code (assuming that "Do something" is the same in both cases).
In terms of performance, the difference should be negligible. The second case does generate twice as many locals in the compiled IL, but the JIT should notice that their usage does not overlap and optimize them away. The second case is also going to cause emission of the same code twice (if (value == theValueWeWant) { ...), but this should also not cause any significant performance penalty.
(Though both aspects of the second example will cause the compiled assembly to be very slightly larger, more IL does not always imply worse performance.)
Both examples do two different things:
Version 1 will run the same code if you get the desired value, where as Version 2 will potentially run different code even if you get the desired value.
There's a lot of possible (micro)optimizations you could do.
For Example, if distance is only ever used in getValue(distance), you could get rid of it entirely:
/*Waring, micro-optimization!*/
public void test() {
EnumType value = getValue((anotherValue == something) ? 10 : (anotherValue == somethingElse) ? 20 : 0);
if (value == theValueWeWant){
//Do something
}
}
If you wish to use those later on, then g for the second method. Those variables will be lost as soon as they're out of scope.
Even if you don't want to use them later, declaring them before the if's is something you should do, to avoid code repetition.
This question is purely a matter of style and hence has no correct answer, only opinions
The C# best practice is generally to declare variables in the scope where they are used. This would point to the second example as the answer. Even though the types and names are the same, they represent different uses and should be constrained to the blocks in which they are created.

Objects with many value checks c#

I want to see your ideas on a efficient way to check values of a newly serialized object.
Example I have an xml document I have serialized into an object, now I want to do value checks. First and most basic idea I can think of is to use nested if statments and checks each property, could be from one value checking that it has he correct url format, to checking another proprieties value that is a date but making sue it is in the correct range etc.
So my question is how would people do checks on all values in an object? Type checks are not important as this is already taken care of it is more to do with the value itself. It needs to be for quite large objects this is why I did not really want to use nested if statements.
Edit:
I want to achieve complete value validation on all properties in a given object.
I want to check the value it self not that it is null. I want to check the value for specific things if i have, an object with many properties one is of type string and named homepage.
I want to be able to check that the string in the in the correct URL format if not fail. This is just one example in the same object I could check that a date is in a given range if any are not I will return false or some form of fail.
I am using c# .net 4.
Try to use Fluent Validation, it is separation of concerns and configure validation out of your object
public class Validator<T>
{
List<Func<T,bool>> _verifiers = new List<Func<T, bool>>();
public void AddPropertyValidator(Func<T, bool> propValidator)
{
_verifiers.Add(propValidator);
}
public bool IsValid(T objectToValidate)
{
try {
return _verifiers.All(pv => pv(objectToValidate));
} catch(Exception) {
return false;
}
}
}
class ExampleObject {
public string Name {get; set;}
public int BirthYear { get;set;}
}
public static void Main(string[] args)
{
var validator = new Validator<ExampleObject>();
validator.AddPropertyValidator(o => !string.IsNullOrEmpty(o.Name));
validator.AddPropertyValidator(o => o.BirthYear > 1900 && o.BirthYear < DateTime.Now.Year );
validator.AddPropertyValidator(o => o.Name.Length > 3);
validator.Validate(new ExampleObject());
}
I suggest using Automapper with a ValueResolver. You can deserialize the XML into an object in a very elegant way using autommaper and check if the values you get are valid with a ValueResolver.
You can use a base ValueResolver that check for Nulls or invalid casts, and some CustomResolver's that check if the Values you get are correct.
It might not be exacly what you are looking for, but I think it's an elegant way to do it.
Check this out here: http://dannydouglass.com/2010/11/06/simplify-using-xml-data-with-automapper-and-linqtoxml
In functional languages, such as Haskell, your problem could be solved with the Maybe-monad:
The Maybe monad embodies the strategy of combining a chain of
computations that may each return Nothing by ending the chain early if
any step produces Nothing as output. It is useful when a computation
entails a sequence of steps that depend on one another, and in which
some steps may fail to return a value.
Replace Nothing with null, and the same thing applies for C#.
There are several ways to try and solve the problem, none of them are particularly pretty. If you want a runtime-validation that something is not null, you could use an AOP framework to inject null-checking code into your type. Otherwise you would really have to end up doing nested if checks for null, which is not only ugly, it will probably violate the Law of Demeter.
As a compromise, you could use a Maybe-monad like set of extension methods, which would allow you to query the object, and choose what to do in case one of the properties is null.
Have a look at this article by Dmitri Nesteruk: http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad
Hope that helps.
I assume your question is: How do I efficiently check whether my object is valid?
If so, it does not matter that your object was just deserialized from some text source. If your question regards checking the object while deserializing to quickly stop deserializing if an error is found, that is another issue and you should update your question.
Validating an object efficiently is not often discussed when it comes to C# and administrative tools. The reason is that it is very quick no matter how you do it. It is more common to discuss how to do the checks in a manner that is easy to read and easily maintained.
Since your question is about efficiency, here are some ideas:
If you have a huge number of objects to be checked and performance is of key importance, you might want to change your objects into arrays of data so that they can be checked in a consistent manner. Example:
Instead of having MyObject[] MyObjects where MyObject has a lot of properties, break out each property and put them into an array like this:
int[] MyFirstProperties
float[] MySecondProperties
This way, the loop that traverses the list and checks the values, can be as quick as possible and you will not have many cache misses in the CPU cache, since you loop forward in the memory. Just be sure to use regular arrays or lists that are not implemented as linked lists, since that is likely to generate a lot of cache misses.
If you do not want to break up your objects into arrays of properties, it seems that top speed is not of interest but almost top speed. Then, your best bet is to keep your objects in a serial array and do:
.
bool wasOk = true;
foreach (MyObject obj in MyObjects)
{
if (obj.MyFirstProperty == someBadValue)
{
wasOk = false;
break;
}
if (obj.MySecondProperty == someOtherBadValue)
{
wasOk = false;
break;
}
}
This checks whether all your objects' properties are ok. I am not sure what your case really is but I think you get the point. Speed is already great when it comes to just checking properties of an object.
If you do string compares, make sure that you use x = y where possible, instead of using more sophisticated string compares, since x = y has a few quick opt outs, like if any of them is null, return, if the memory address is the same, the strings are equal and a few more clever things if I remember correctly. For any Java guy reading this, do not do this in Java!!! It will work sometimes but not always.
If I did not answer your question, you need to improve your question.
I'm not certain I understand the depth of your question but, wouldn't you just do somthing like this,
public SomeClass
{
private const string UrlValidatorRegex = "http://...
private const DateTime MinValidSomeDate = ...
private const DateTime MaxValidSomeDate = ...
public string SomeUrl { get; set; }
public DateTime SomeDate { get; set; }
...
private ValidationResult ValidateProperties()
{
var urlValidator = new RegEx(urlValidatorRegex);
if (!urlValidator.IsMatch(this.Someurl))
{
return new ValidationResult
{
IsValid = false,
Message = "SomeUrl format invalid."
};
}
if (this.SomeDate < MinValidSomeDate
|| this.SomeDate > MinValidSomeDate)
{
return new ValidationResult
{
IsValid = false,
Message = "SomeDate outside permitted bounds."
};
}
...
// Check other fields and properties here, return false on failure.
...
return new ValidationResult
{
IsValid = true,
};
}
...
private struct ValidationResult
{
public bool IsValid;
public string Message;
}
}
The exact valdiation code would vary depending on how you would like your class to work, no? Consider a property of a familar type,
public string SomeString { get; set; }
What are the valid values for this property. Both null and string.Empty may or may not be valid depending on the Class adorned with the property. There may be maximal length that should be allowed but, these details would vary by implementation.
If any suggested answer is more complicated than code above without offering an increase in performance or functionality, can it be more efficient?
Is your question actually, how can I check the values on an object without having to write much code?

How do I ensure the value of property for others that are dependent upon it?

I have a property like so:
private Decimal _payout;
public Decimal PayoutValue
{
get { return _payout; }
set
{
_payout = value;
//second part of following conditional is an enum
if (Math.Abs(value) > 1 && this.PayoutType == CutType.Percent)
{
_payout /= 100;
}
}
}
As you can see, it is dependent upon the value of PayoutType, which is just a simple enum property:
public CutType PayoutType { get; set; }
My problem is that PayoutType doesn't seem to get set before PayoutValue is set, so the conditional below is never true. How do I force the PayoutType to be set before PayoutValue is evaluated?
Thanks.
UPDATE Thanks for your answers guys. I guess I should have mentioned that most of the time this object is bound via DataContexts or from an Http.Post from my client side (MVC project), so I don't really have any constructors. Is there any other way, or should I start getting creative with my programming?
How do I force the PayoutType to be set before PayoutValue is evaluated?
Put it in the constructor. That's the only way to enforce this rule.
That being said, I would recommend against this, at least in your implementation above. Your current property implementation will be very, very confusing to users. People tend to expect that setting a property, then immediately fetching it will provide the same value.
In your case, though:
decimal value = 45.3;
myObject.PayoutValue = value; // Set this
if (myObject.PayoutValue != value)
{
// This would normally be a very unexpected case! In your example, it will always be true!
}
It would be much better to potentially use two properties, or a method (ie: SetPayoutValue(decimal value)) to clue the user into the fact that it's not acting like a simple property.
How about this ?
get
{
if (Math.Abs(value) > 1 && this.PayoutType == CutType.Percent)
{
return _payout /100;
}
return _payout;
}
set{_payout = value;}
So that you do not change the value that was set.
All "required" properties should be in the constructor of your class.

Should a C# accessor use a private variable or calculate on the fly?

Which is a better programming practice and why?
I have a class like this:
class data {
public double time { get; internal set; }
public double count { get; internal set; }
public average_count { ... }
}
Where average_count should be read_only and give a calculation of count / time.
Is it better to write the accessor as:
public average_count { get {
return (time == 0) ? 0 : (count / time);
}}
Or should I do something like:
private _avg_count;
public average_count {
get
{
return _avg_count;
}
internal set
{
return _avg_count;
}
}
Where _avg_count is updated when in the time and count set accessors?
It seems like the first is easier to read but may be slower if average_count is accessed often. Will the compiler optimizations make the difference insignificant?
Doing it on the fly results in more readable code. Precalculating may improve performance, but you should only do this if (a) it's necessary and (b) you've profiled and it makes a difference.
The bottom line is, readability and maintainability should only be sacrificed for performance when it's absolutely necessary.
This is such a seemingly simple question, yet it's almost impossible to answer. The reason is that what's "right" depends on a number of factors.
1. Performance
In his answer Skilldrick recommends that you prefer what is readable over what performs best as a general rule:
[R]eadability and maintainability should
only be sacrificed for performance
when it's absolutely necessary.
I would counter this by saying that it is only true in a typical business application, where performance and functionality are two clearly distinguishable features. In certain high-performance software scenarios, this is not such an easy thing to say as performance and functionality may become inextricably linked -- that is, if how well your program accomplishes its task depends on how solidly it performs (this is the case at my current place of employment, a company that does algorithmic trading).
So it's a judgment call on your part. The best advice is to profile whenever you have an inkling; and if it's appropriate to sacrifice readability for performance in your case, then you should do so.
2. Memory Usage
0xA3 suggests a fairly elegant approach providing a compromise of sorts: only calculate the value as needed, and then cache it.
The downside to this approach, of course, is that it requires more memory to maintain. An int? requires essentially the same amount of memory as an int plus a bool (which, due to alignment issues, could actually mean 64 bits instead of just 40). If you have loads and loads of instances of this data class and memory is a scarce resource on the platform you're targeting, bloating your type with another 32 bits per instance might not be the smartest move.
3. Maintainability
That said, I do agree in general with what others have said that, all else being equal, you're better off erring on the side of readability so that you can understand your code if and when you revisit it in the future. However, none of the various approaches to this problem is particularly complicated, either.
The bottom line is that only you know your exact circumstances and thus you are in the best position to decide what to do here.
It depends how often you will call average_count and how often count and time are modified. For such kind of optimization I would suggest you to use profiler.
In cases where performance is critical and you need to frequently access the property you have another option as well: Calculating the result when it is needed and then cache the result. The pattern would look like this:
class Foo
{
int? _cachedResult = null;
int _someProperty;
public int SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; _cachedResult = null; }
}
int _someOtherProperty;
public int SomeOtherProperty
{
get { return _someOtherProperty; }
set { _someOtherProperty = value; _cachedResult = null; }
}
public int SomeDerivedProperty
{
get
{
if (_cachedResult == null)
_cachedResult = someExpensiveCalculation();
return (int)_cachedResult;
}
}
}
In this simple case, I would definitely implement the calculated version first; then optimize if neccessary. If you store the value, you will also need extra code to recalculate the value if any of the values it depends on, changes, which leads to possibilities for errors.
Don't optimize prematurely.
I'd go with your first option. These are in-memory objects so the computation on what you're doing is going to be extremely fast. Further, if you created a dedicated property for this (e.g., average_count) then you're going to have to add more code to re-calculate this in the setter for both the time and the count.
As a side note (since you're asking about best practice), you should be using Pascal casing in C# which is initial caps and no underscores.
Will the compiler optimizations make the difference insignificant?
Depends on what you consider "significant". Reading a varaible is rather quick. Dividing two number is rather quick. In fact, depending on what in the RAM cache, reading the variables may take longer than doing the divide.
Use the first method. If it's seems to slow, then consider the second.
If you care about thread safety it may be way easier to do the second option rather than the first.
private double _avg_count;
static readonly object avgLock = new object();
public double time { get; internal set; }
public double count { get; internal set; }
public double average_count {
get
{
return _avg_count;
}
}
private void setAverageCount()
{
_avg_count = time == 0 ? 0 : (count / time);
}
public void Increment()
{
lock (avgLock)
{
count += 1;
setAverageCount();
}
}
public void EndTime(double time)
{
lock (avgLock)
{
time = time;
setAverageCount();
}
}

Getter/Setter problem in C#

I am doing
static bool isWorking
{
get { return _isWorking; }
set {
myform.treeView1.Enabled = !value;
_isWorking = value;
}
}
and stepping through the debugger shows it stops at the first set line.
After trying this line instead
set { myform.treeView1.Enabled = !(_isWorking = value); }
I see that isWorking is set but myform.treeView1.Enabled is not. Whats going on?
What do you mean by "the debugger shows it stops"? Is it possibly that myform is null, or myform.treeView1 is null?
I can't remember the exact evaluation order in this case, but it could explain the symptoms you're describing. Knowing why the debugger "stops" is crucial though. Another possibility is that you're trying to access the UI from a non-UI thread, which would prevent the assignment to Enabled from working properly.
Oh, and please don't use your second version - assignment as a side-effect is very, very rarely a good idea. The only idiomatic use I know is when looping with IO:
string line;
while ( (line = reader.ReadLine()) != null)
and I only consider that acceptable because it's reasonably common. In this case it really looks like you could mean "==" instead of "=".
Because (_isWorking = value) returns always true. If you would write:
myform.treeView1.Enabled = !(_isWorking == value);
It works like: if isWorking is equal to value then Disable treeView. But in you case - no

Categories