VS2010 keeps telling me that a CodeContract.Invariant is false. I can't see how this can possibly be the case
public class BankAccountIdentifierDefinitionVariation_CreateCommandArgs : ValidatedCommandArgs
{
public string IdentifierCode {get; private set; }
public string CountryCode {get; private set; }
public Ems.Infrastructure.Validation.StringValidator Validator {get; private set; }
private BankAccountIdentifierDefinitionVariation_CreateCommandArgs()
: base() { }
public BankAccountIdentifierDefinitionVariation_CreateCommandArgs(
string identifierCode,
string countryCode,
Ems.Infrastructure.Validation.StringValidator validator)
{
Contract.Requires(!string.IsNullOrEmpty(identifierCode));
Contract.Requires(!string.IsNullOrEmpty(countryCode));
Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode));
Contract.Ensures(!string.IsNullOrEmpty(this.CountryCode));
this.IdentifierCode = identifierCode;
this.CountryCode = countryCode;
}
[ContractInvariantMethod]
void ContractInvariants()
{
Contract.Invariant(!string.IsNullOrEmpty(IdentifierCode));
Contract.Invariant(!string.IsNullOrEmpty(CountryCode));
}
}
The warning is that both invariants are false, which obviously cannot be the case. I have also tried the two following variations.
Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode);
if (string.IsNullOrEmpty(identifierCode)) throw new ArgumentNullException...
this.IdentifierCode = identifierCode;
and also
Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode));
this.IdentifierCode = identifierCode;
if (string.IsNullOrEmpty(this.IdentifierCode)) throw new ArgumentNullException...
It looks as if the invariant is false because it is possible for me to change the value of the property via its private setter (even though I do not.) Is there a way to deal with this? The properties must remain properties because I am serializing.
It seems that the static analyzer fails to see that the parameterless constructor is never invoked. Maybe its existance is enough to question your invariant.
Can you remove it altogether? If you already have a constructor, why do you need a private parameterless one?
I would expect the private default constructor to be the source of the warning, since executing that would indeed violate the invariant. However since you have a constructor defined there's nothing stopping you from deleting the default constructor. If you define at least one constructor the compiler will not emit a default contructor on your behalf and since you are never using the default constructor there's no reason to have it in the first place
Related
I know there are a few questions on stack overflow on this already but I haven't found any that answer my specific question. I came from a java development background and never bothered using the get; set; methods from C# until now.
I have the following code
class Test
{
public int test { get; set; }
}
In my main function I can declare a new Test and use t.Test = 5 and that works fine; however, when I switch the public to private I cannot access my get; and set; methods anymore... BUT when I use (Similar method to Java)
class Test
{
private int test;
public int getTest()
{
return this.test;
}
public void setTest(int test)
{
this.test = test;
}
}
I'm confused on the design philosophy. In C# should I no longer be using private variables (Only make it private if it's used internally in the class) and make them all public and use private get; private set; to control accessibility?
When you write this (I'm using different class and property names for clarity):
public class Test
{
public string Name { get; set; }
}
that's asking the compiler to create a private field with a public property. It's equivalent to:
public class Test
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
(Except the field name is autogenerated and not directly representable in C#.)
That's basically equivalent to what you'd write in Java as:
// Java
public class Test {
private String name;
public String getName() {
return name;
}
public String setName(String name) {
this.name = name;
}
}
... but clearly the C# is a lot more compact.
Basically, C#'s properties make for more readable code than having getter and setter methods as normal methods - but that's all they are, really. They're just used differently in code. The automatically implemented properties (as per the first snippet) make "trivial" properties simpler to express. In C# 6, you can write read-only automatically implemented properties too, which can be assigned to from the constructor but only the constructor.
Importantly though, you're still only making the properties part of the public API - not the fields. So if you later want to add some more logic (e.g. to have two properties derived from the same field, or something like that) you can do so without affecting either source or binary compatibility.
and make them all public and use
private get; private set; to control accessibility?
No, not really. Let's have a look at this scenario:
private int _a;
public int A
{
get { return _a; }
private set { _a = value; }
}
So this field _a is encapsulated and cannot be accesed from anywhere except the same class. But A is a public property and it is inside the class so it can access _a field and work with it however its set accessor is private, so it cannot be accessed from outside of the class...
But to do something like this usually makes little sense :
private int MyProperty { get; set; }
Ok, we created auto-implemented property to access private fields that it work with. But this property is private (used only inside the same class) and because it's auto-implemented it cannot contain any logic inside.
But if change it to :
public int MyProperty { get; private set; }
It's more useful and the main difference from first example is that it creates backing field automatically. Though it still impossible to add some logic but it encapsulates setter method and it's a way of creating read-only properties (at least read-only outside of class).
The other answer is true but I think it misses something important.
When you have:
class Test
{
public int test { get; set; }
}
There is an unseen, private variable in your class called something like _test. This is not accessible outside of the class and is accessed with get and set with set. For the most part, you won't change those methods, but the option is there for you in the future if you want to.
What you are using here are Auto-Implemented Properties.
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In other words, the two code blocks you posted are functionally the same.
The part that might not be obvious is that you also can declare either the getter or setter private, not necessarily the whole property, i.e.
public int test { get; private set; }
which would make it possible to get the value, but impossible to set the value from outside the class.
However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties (C# Programming Guide).
Yes, you use private variables only when you need to scope things internally to your class. They're obviously not visible from the outside.
The main reason for using Properties as they are known is when you want to add logic to your gets or sets. Say you want to validate a value before assignment, or you may want to delay load values and cache them in a get etc.
Here is a typical example when you'd want to use a property, over a simple value field:
private float latitude;
public float Latitude {
get { return this.latitude; }
set {
if(value < -90 || value > 90)
{
throw new ArgumentOutOfRangeException("Invalid Latitude");
}
this.latitude = value;
}
}
Now you could quite easily make the property private too, but you'd still be able to embed logic in there, obviously just not access it from outside. A singleton pattern is an example that springs off the top of my head.
You can also make the setting private for a variable. This allows you more flexibility to prevent people updating something they shouldn't, yet still give them access to the variable if need be.
private float latitude;
public float Latitude {
get;
private set;
}
Let say I have a class like this:
public class A
{
private BaseSettings fieldA;
public ISettings PropertyA
{
get {return fieldA;}
set {fieldA= value as BaseSettings;}
}
}
where BaseSettings implements ISettings. Inside class A, if I want to access BaseSettings' property called PropertyB, which of this is a good practice:
fieldA.PropertyB;
or
((BaseSettings)PropertyA).PropertyB;
One may say the first approach may hide the hint to when a property changed. For example, a code may listen to PropertyChangedEvent and then the value for property changed without raising the event.
Another one may say the second approach may expose a risk that when a person who is not familiar with current code modify it, he may cast the PropertyA to different type that implements ISettings.
Both approaches have its downside. In a good programming practice, which one should be more preferable?
EDIT:
Added based on the comments belows:
I agree that setting the backing-field as ISettings makes absolute sense. But what should I do to make sure that the PropertyA is always type of BaseSettings. That will raise a question: "Then why don't you set both property and backing-field to BaseSettings?".
The reason behind why property and its backing field are different is that class A also implement an interface like this
public interface IControlWithSettings
{
ISettings OwnerSettings
{
get;
set;
}
ISettings Settings
{
get;
set;
}
}
So the actual classA would look like this
public class BaseForm: Form, IControlWithSettings
{
private BaseFormSettings settings;
public ISettings Settings
{
get {return settings;}
set {settings= value as BaseFormSettings;}
}
}
And I have another class B would also implement IControlWithSettings
public class BaseUserControl: UserControl, IControlWithSettings
{
private BaseUserControlSettings settings;
public ISettings Settings
{
get {return settings;}
set {settings= value as BaseUserControlSettings ;}
}
}
Both BaseFormSettings : ISettings and BaseUserControlSettings : ISettings . This is actual ISettings interface
public interface ISettings
{
Dictionary<string, ISettings> Children { get; set; }
}
the 'as' casting is a side effect I put into the setter so that it will ignore and return null if the setting is set to wrong one. I read somewhere saying I shouldn't throw exception in a setter. So making it null is my way to inform there is something wrong has been done.
So what is the better approach. Did I design it wrong?
As you stated, both approaches have their downsides, and it also depends on whether the property setter may contain some additional logic (e.g. validation), and you may use or circumvent this additional logic from inside the class.
If there's nothing that speaks against it, I'll use direct access to the field. It's neater and it avoids all this typecasting stuff.
But generally: Why would you back your property with the derived type, while the property itself has the interface type? This doesn't make much sense. Why not just:
public class A
{
public ISettings PropertyA { get; set; }
}
This would be much cleaner, and your question wouldn't even arise.
Edit (based on the answer's edit)
In case of the 'double use' of the backing field the typecasting makes sense. But I don't think (and never heard that before) that it's a bad thing to throw an exception from a property setter. On the contrary: Validating a value and throwing an exception if it doesn't pass is a very common pattern.
So, in your concrete case, I would validate the value for the correct type, throw if it's not correct, and use the backing field internally to bypass this type check.
I am getting a code analysis warning that seems to be a false-positive.
CA1812 : Microsoft.Performance : 'MyClass.MyPrivateClass' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static methods, consider adding a private constructor to prevent the compiler from generating a default constructor.
How do I get rid of this warning? I prefer to not suppress warnings unless I am sure I couldn't avoid it otherwise.
The classes look like this:
namespace Some.Namespace
{
public class MyClass
{
private class MyPrivateClass
{
public int Id { get; set; }
public ModelObject { get; set; }
}
}
}
I use it like this:
private IQueryable<MyPrivateClass> GetMyPrivateClasses()
{
return this.Repository().All()
.Select(m => new MyPrivateClass { Id = m.Id, ModelObject = m };
}
Does this usage not count as instantiation?
I guess it is examining the IL; and genuinely - that IL does not ever contain a new MyPrivateClass instruction - because that statement is presumably running against IQueryable<T>, hence that lambda is an expression tree. It will contain some Expression.New, and some typeof(MyPrivateClass) - but no new MyPrivateClass.
In this case, the error is misleading. Simply suppress it.
FYI there is a new documentation page for this warning:
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1812
Instantiation of classes is not always recognized by analyzers.
Suppress this warning, if justified:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "generic/late bound/reflection")]
Happens especially in Net.Core.
Change your class to internal or public, that solves the problem. Anyway, you can extract your inner class from the outer class...
So I have an object called FixedSizeList that does not have a parameterless constructor.
Looks like this.
class FixedSizeList<T>
{
public FixedSizeList(Int32 size)
{
this.Size = size;
this._Array = new T[size];
}
}
Now I want to use this object as a property of another class as such.
public FixedSizeList<Card> CardList { get; set; }
I have noticed that I can infact declare the property with a constructor.
public new FixedSizeList<Card> CardList { get; set; }
But the problem is that the FixedSizeList is not instantiated (I guess for obvious reasons).
So shouldn't I either get a compile time error (something like "No parameterless constructor declared for object") for this code or infact be somehow able to declare the parameter in the property?
Could someone please explain what is going on and if there is someway to fix this problem?(Obviously I can do all this in the constructor of the second object but I am trying to look at other techniques).
Putting new in front of a property doesn't cause the property's setter to be magically called at initialization time and passed a new instance of that type (that would be quite a load of implications for a tiny little keyword!)
Rather, it's used to hide a member with the same name on a base class.
If you want your property to return a new instance right away, you need to give it a backing that's initialized:
public FixedSizeList<Card> CardList
{
get { return _cardList; }
set { _cardList = value; }
}
private FixedSizeList<Card> _cardList = new FixedSizeList<Card>(99999999);
what you want to do is something of a factory
you need a static method that will return you an instance of the object, inside your class
public static FixedListSize GetInstance() {
return new FixedListSize();
}
I can't remember though if you have to mark the class as static, i think you may have to. it's escaping me at the moment :\
I've seen a lot of example code written using something like (please forgive how horribly canned this is):
public class Test
{
public object Thingy { get; private set; }
}
Unfortunately, these kinds of examples never really explain why 'set' is set as private. So, I'm just wondering if there's a good, common example that will illustrate to me why something like this would be used.
I sort of see it - the property can be run to process some extra logic in addition to setting that field. I'm just confused on how it would be invoked, and why this approach would be used rather than a generic setter method.
This would be if you have a property that you don't want anyone to set but your class. This can be handy with database id's. The internal class can set it but you wouldn't want anyone else changing it. So you can give them read access but not write.
EDIT: One more point on this is that using what you showed there is helpful for automatic properties. Unfortunately with automatic properties you are unable to only specify get so to avoid exposing a setter publicly it is just made private.
EDIT: Just thought I would throw in an example. Automatic properties are great for clean, terse code. But like you showed there is a limitation in that you have to have get and set. So before it was like this for a property like you showed:
public class Test
{
private object thingy;
public object Thingy
{
get { return thingy; }
}
}
Now we can get rid of that unneeded private declaration but it requires both. So make private to get around that.
I know this was overkill on the explanation but different things kept popping in my head.
As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).
Another example might be a list:
public List<Foo> Items {get;private set;}
since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items {get { return items;}}
which solves both of these.
As another example, contrasting:
private readonly int foo;
public int Foo {get{return foo;}}
vs
private readonly int foo;
public int Foo {get{return foo;} private set {foo=value;}}
this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.
Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.
The private makes it into a readonly property. A common example is if you have multiple classes passing around a single object, you don't want another class to be able to modify the instance.
Basically, it is a readonly property. If it was written in full (not as an auto property) you would simply leave out the setter.
Two examples that are largely the same:
class Foo1
{
public int Id { get; private set; }
public Foo1()
{
Id = lastId ++;
}
}
class Foo2
{
private int _id;
public int Id { get { return _id; } }
public Foo2()
{
_id = lastId ++;
}
}
I've seen this used with the design:
public class whatever
{
public string WhateverId { get; private set; }
public static whatever Create(string whateverId)
{
return new whatever() { WhateverId = whateverId };
}
}
So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.
the private set just gives the simple initializer syntax, I kind of like it for some scenarios.
Also can be used if it's changeable, but you need to manage it when changes are made
public void SetWhateverId(string whateverId)
{
DisconnectAllCurrentWhateverIdReferences();
WhateverId = whateverId;
ReconnectAllPreviousWhateverIdReferences();
}
This syntax allows you to provide a public-facing property that appears read-only to consumers of your API but internally can be changing. By auto-implementing in this way, you avoid having to write boilerplate code such as a distinct setter or a backing field for the value, and you leave room in your design to add a bespoke set algorithm if it is deemed necessary at some point in the future without having to decide right away.
private set is very handy for simple immutable value types.
struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
{
this = default(Point);
X = x;
Y = y;
}
}
This is just laziness that comes about from auto-properties. Before auto properties were around, people would implement the getter and omit the setter for properties which are meant to be read-only.
public class Test
{
private /*readonly*/ Type _thingy;
public Type Thingy { get { return _thingy; } }
}
Hopefully, C# 5 will allow you to create auto-properties with a getter only - because that's what everyone wants. (They should make readonly setters in auto-props too, I need that badly)
To answer the question of a common scenario where this might be used...
In an MVP pattern, if your Model exposes some properties for your Presenter I would write
public string Bazinga { get; private set; }
Now, the Model can change this value but other classes that use it cannot.