Unproven Ensure that references another property in combination with an interface - c#

Assume the following code:
[ContractClass(typeof(ICC4Contract))]
public interface ICC4
{
bool IsFooSet { get; }
string Foo { get; }
}
public class CC4 : ICC4
{
private string _foo;
public bool IsFooSet { get { return Foo != null; } }
public string Foo { get { return _foo; } }
}
[ContractClassFor(typeof(ICC4))]
public abstract class ICC4Contract : ICC4
{
public bool IsFooSet
{
get
{
Contract.Ensures((Contract.Result<bool>() && Foo != null)
|| !Contract.Result<bool>());
return false;
}
}
public string Foo
{
get
{
Contract.Ensures((Contract.Result<string>() != null && IsFooSet)
|| !IsFooSet);
return null;
}
}
}
The contracts try to say:
IsFooSet will return true if Foo is not null.
Foo doesn't return null if IsFooSet returns true.
This almost works.
However, I get an "ensures unproven" on return _foo;, because the checker doesn't realize that Foo will always equal _foo.
Changing Foo to an automatic property with a private setter removes that warning, but I don't want to do that (I don't like automatic properties with private setters).
What do I have to change in the above code to make the warning go away while preserving the _foo field?
The following doesn't work:
Changing IsFooSet to use _foo instead of Foo. It will result in an additional "ensures unproven" on IsFooSet.
Adding an invariant Foo == _foo. This will result in an "invariant unproven" on the implicit, default constructor. Furthermore, on a real code-base the processing time of the static checker will be magnitudes higher.
Adding Contract.Ensures(Contract.Result<string>() == _foo); to the getter of Foo as per this answer doesn't change anything.

You can use short-circuiting to simplify the condition, and that works for some reason:
[ContractClassFor(typeof(ICC4))]
public abstract class ICC4Contract : ICC4
{
public bool IsFooSet
{
get
{
Contract.Ensures(!Contract.Result<bool>() || Foo != null);
return false;
}
}
public string Foo
{
get
{
Contract.Ensures(!IsFooSet || Contract.Result<string>() != null);
return null;
}
}
}

Related

Comparing a class instance with another, which contain matching values

I get that one instance of a class is not equal to another instance of the same class, even if both instances contain the properties & fields of the instances contain the same values. For example, in the below code, even though both instances of TestClass have the same value for the TestValue01 and TestValue02 properties, the comparison will equate to false and "Boooo!" will be printed.
static void Main(string[] args)
{
TestClass testClassInstance01 = new TestClass(1, 1);
TestClass testClassInstance02 = new TestClass(1, 1);
if (testClassInstance01 == testClassInstance02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
}
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
}
Is it at all possible to force this kind of comparison to equate to true?
The obvious thing to do is to compaire the property values, like below, but I'm curious if this can be avoided.
if (testClassInstance01.TestValue01 == testClassInstance02.TestValue01
&& testClassInstance01.TestValue02 == testClassInstance02.TestValue02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
EDIT
For completeness, what I was looking for was operator overloading. Here is the code I require for this example to return true:
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
public static bool operator==(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 == tc02.TestValue01 && tc01.TestValue02 == tc02.TestValue02;
}
public static bool operator!=(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 != tc02.TestValue01 || tc01.TestValue02 != tc02.TestValue02;
}
}
Marij Khans answer is basically correct. Without overloading the operator(s) ReferenceEquals(object, object) is used for '==' and '!=' when applied to class instances and, because in your example you compare two instances, the result is 'false'. The full blown solution looks like this:
public class TestClass : IEquatable<TestClass>
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
public override bool Equals(object obj)
{
return Equals(obj as TestClass);
}
public bool Equals(TestClass other)
{
return other != null &&
TestValue01 == other.TestValue01 &&
TestValue02 == other.TestValue02;
}
public static bool operator ==(TestClass test1, TestClass test2)
{
return EqualityComparer<TestClass>.Default.Equals(test1, test2);
}
public static bool operator !=(TestClass test1, TestClass test2)
{
return !(test1 == test2);
}
}
Besides the overloading of the operators '==' and '!=' the implementation of the IEquatable interface ensures that comparisons always work as expected, even when used as key in a dictionary or the pattern a.Equals(b) is used. For better speed when searching large collections with instances of this class as key, you might even want to implement GetHashCode(), but that requires that the values used when generating the hash code have to be readonly (i.e. removing the setter of the properties, so they can only be set from within the constructor).
Overload the == operator. I haven’t done c# in a while so I’m a little rusty but you can take a look at operator overloading to define this type of behaviour

How can I verify whether a Func<> property has been initialized?

I have a Func property on my class as below.
public class ClassA {
public Func<string, IClassB> MyProperty { get; set; }
}
Checking MyProperty for null is not possible. Therefore my question is if it it possible to verify that MyProperty has been initialized in some way?
EDIT: I wasn't giving you my whole picture because i beleived it was exactly the same for Func in general. Sorry for that.
Thing is that I am actually instantiating the property using reflection and ahead of this I pick up the value of MyProperty to set it only when it is not instantiated.
...
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (Attribute.IsDefined(property,typeof(WireAttribute)))
{
var propertyValue = property.GetValue(objectToWire, null);
if (propertyValue == null) //<-- THIS IS NOT TRUE FOR FUNC RETURN TYPES
...
For regular properties, not Func return type it works as expected.
ClassA clsA = new ClassA();
if (clsA.MyProperty == null)
MessageBox.Show("IsNull");
clsA.MyProperty = new Func<string, bool>(x => x.Equals("1"));
MessageBox.Show(clsA.MyProperty == null ? "IsNull" : "IsNotNull");
this works very good
If I take your code and do
var a = new ClassA();
var initialized = a.MyProperty == null;
the code is perfectly valid. Therefore your assertion is incorrect, checking for null is possible.
What are you trying to achieve, perhaps you want something like.
public class ClassA
{
private readonly Func<string, IClassB> myFunc;
public ClassA(Func<string, IClassB> myFunc)
{
this.myFunc = myFunc;
}
public IClassB MyFunc(string input)
{
if (this.myFunc = null)
{
return null;
}
return this.myFunc(input);
}
}
At runtime, you can check if the property has been initialized. What you can't check is the value returned by it's invocation, as the invocation is dynamic.
class Program
{
interface IClassB { }
class ClassB1 : IClassB { }
class ClassB2 : IClassB { }
class ClassA
{
public Func<string, IClassB>
MyProperty { get; set; }
}
static void Main(string[] args)
{
var classA = new ClassA();
Console.WriteLine((classA.MyProperty == null)
? "Not initialized" : "Initialized");
classA.MyProperty = (a) =>
{
if (a == "1")
return new ClassB1();
else if (a == "2")
return new ClassB2();
else
return null;
};
Console.WriteLine((classA.MyProperty == null)
? "Not initialized" : "Initialized");
object
c1 = classA.MyProperty.Invoke("1"),
c2 = classA.MyProperty.Invoke("2"),
c3 = classA.MyProperty.Invoke("3");
Console.WriteLine((c1 != null) ? c1.GetType().Name : "null");
Console.WriteLine((c2 != null) ? c2.GetType().Name : "null");
Console.WriteLine((c3 != null) ? c3.GetType().Name : "null");
}
}
Apart from the other answers, you may use a property for the Func (if you want/can to test this inside ClassA):
public class ClassA {
private Func<string, IClassB> myProperty;
public Func<string, IClassB> MyProperty {
get {
if (myProperty == null)
return some default behaviour;
return myProperty;
}
set {
myProperty = value;
}
}
You can check it by standard means, like this:
IClassB a = new IClassB();
//it is null now so Empty will follow
if (a.MyProperty == null) Console.WriteLine("Empty");
else Console.WriteLine("Not empty");
a.MyProperty = new Func<string, IClassB>((s)=>{ return new IClassB(); });
//it is not null now so Not empty will follow
if (a == null) Console.WriteLine("Empty");
else Console.WriteLine("Not empty");

Constrain generic to be a nullable type

I'm looking for sample usage something like this:
Foo<string> stringFoo = new Foo<string>("The answer is");
Foo<int> intFoo = new Foo<int>(42);
// The Value of intFoo & stringFoo are strongly typed
stringFoo.Nullify();
intFoo.Nullify();
if (stringFoo == null && intFoo == null)
MessageBox.Show("Both are null);
Given this class Foo, I can auto-wrap T into a nullable:
public class Foo1<T>
where T : struct
{
private T? _value;
public Foo(T? initValue)
{
_value = initValue;
}
public T? Value { get { return _value; } }
public void Nullify { _value = null; }
}
This works for primitives, but not with String or other classes.
Next flavor works for strings, but not primitives:
public class Foo2<T>
{
private T _value;
public Foo(T initValue)
{
_value = initValue;
}
public T Value { get { return _value; } }
public void Nullify { _value = default(T); }
}
I could use Nullable<int> for Foo2 and the code would work like this:
Foo2<int?> intFoo = new Foo<int?>(42);
But this is error prone because it fails for Foo2. If I could constrain T to be types that support nullability then that would be fine.
So after all of that, is there any way to constrain T to be a nullable type?
Some additional notes: .NET 4.0, VS2010. And I did find one similar question to this on here, but without a succesful answer.
There's no constraint you can apply for this, but you can test for it at execution time:
if (default(T) != null)
{
throw new SomeAppropriateException(typeof(T) + " is not a nullable type");
}
You could even put that into a static constructor, which would make sure it only executed once per constructed type - and anyone trying to use Foo<int> anywhere would have a hard time ignoring the TypeInitializerException. That's not terribly friendly for a public API, but I think it's reasonable for an internal one.
EDIT: There is one horrible way of making it harder to create instances of Foo<int>... you could use the ghastly code in this blog post (using overload resolution rules along with default parameters and a couple of constrained generic types) and mark the overload which aims at a non-nullable value type as obsolete with an error. That way, Foo<int> would still be a valid type, but you'd be hard-pressed to create an instance of it. I'm not going to recommend that you do this though...
You might be able to make the constructor of Foo<T> internal, and require that new instances can only be created through a factory class:
public class Foo<T>
{
private T value;
internal Foo(T value)
{
this.value = value;
}
public void Nullify()
{
this.value = default(T);
}
public T Value { get { return this.value; } }
}
public class Foo
{
public static Foo<T> Create<T>(T value) where T : class
{
return new Foo<T>(value);
}
public static Foo<T?> Create<T>(T? value) where T : struct
{
return new Foo<T?>(value);
}
}
I don't like it as much as the syntax of Foo1, but here is Foo3:
public class Foo3<T>
where T : struct
{
private T _value;
private T _nullValue;
public Foo3(T initValue)
: this(initValue, default(T))
{
}
public Foo3(T initValue, T nullValue)
{
_value = initValue;
_nullValue = nullValue;
}
public T Value { get { return _value; } }
public bool IsNull
{
get
{
return object.Equals(_value, _nullValue);
}
}
public void Nullify() { _value = _nullValue; }
}
And then my usage becomes:
Foo3<string> stringFoo = new Foo<string>("The answer is");
Foo3<int> intFoo = new Foo<int>(42, int.MinValue);
stringFoo.Nullify();
intFoo.Nullify();
if (stringFoo.IsNull && intFoo.IsNull)
MessageBox.Show("Both are null);
This is still error prone because getting the Value property of Foo3 (and Foo2) is not straightforward. Foo1 was the best because automatically wrapped the Value will null support.
I might just need ValueTypeFoo and ObjectFoo and deal with two versons.

Enable static contract checker to prove a Property non-null based on some other property

Assume the following code:
public class CC3
{
private string _field;
private bool _someFlag;
public string Property
{
get { return _field; }
}
public bool SomeFlag
{
get { return _someFlag; }
}
public void SetField()
{
_field = " foo ";
_someFlag = true;
}
public string Method()
{
Contract.Requires(SomeFlag);
return Property.Trim();
}
}
The static checker of Code Contracts complains about the return statement of Method:
Possibly calling a method on a null reference 'this.Property'
What do I have to do to enable the static checker to prove that Property can never be null if SomeFlag is true?
You can give the static analysis a helping hand using Contract.Assume:
public string Method()
{
Contract.Requires(SomeFlag);
Contract.Assume(Property != null);
return Property.Trim();
}
Or actually add the check as a Contract.Requires in its own right. After all, just because you can manually prove it to be true for now, you can't guarantee that will always be the case when the code gets modified. In fact, consider whether SomeFlag being true is actually a requirement at all. Perhaps this is a cleaner solution:
public string Method()
{
Contract.Requires(Property != null);
return Property.Trim();
}
The only way to prove that it is not null is to prove that it is not null. Ideally you could use an invariant if you would convert to auto properties. For this example you could rewrite the property to ensure that null is not a possible result:
public string Property
{
get {
Contract.Ensures(Contract.Result<string>() != null);
return _field ?? String.Empty;
}
}

Can you check for null when a constructor call another constructor using the object given to the first constructor?

If I have a class with two constructors as follows:
class Foo
{
public Foo(string name)
{...}
public Foo(Bar bar): base(bar.name)
{...}
}
is there some way that I can check if bar is null before I get a null reference exception?
You can use a static method to do this:
class Foo
{
public Foo(string name) {
...
}
public Foo(Bar bar): base(GetName(bar)) {
...
}
static string GetName(Bar bar) {
if(bar == null) {
// or whatever you want ...
throw new ArgumentNullException("bar");
}
return bar.Name;
}
}
class Foo
{
public Foo(Bar bar): base(bar == null ? default(string) : bar.name)
{
// ...
}
}
alternatively let the bar-class handle with an object of the bar-class and throw an ArgumentNullException if you'd like
public Foo(Bar bar): base(bar == null ? "" : bar.name)
{...}

Categories