When NOT TO USE 'this' keyword? - c#

Sorry for asking it again, there are already some questions about this keyword. But all of them tell the purpose of 'this'.
When do you use this keyword
C# when to use this keyword
Use of “this” keyword in formal parameters for static methods in C#
Proper usage of “this.” keyword in C#?
My question is when not to use 'this' keyword .
OR
Is it all right to use this keyword always in situation like the code
class RssReader
{
private XmlTextReader _rssReader;
private XmlDocument _rssDoc;
private XmlNodeList _xn;
protected XmlNodeList Item { get { return _xn; } }
public int Count { get { return _count; } }
public bool FetchFeed(String url)
{
this._rssReader = new XmlTextReader(url);
this._rssDoc = new XmlDocument();
_rssDoc.Load(_rssReader);
_xn = _rssDoc.SelectNodes("/rss/channel/item");
_count = _xn.Count;
return true;
}
}
here i have not used 'this' with "_xn" and "_count" also not with "_rssDoc.Load(_rssReader);" is it fine? Should i use "this" with all occurrences of class variables within the class?
Edit: Is it useless to use 'this' in a class for its own variables?

I always use this. I use the same naming convention for local variables and private fields and it makes the code much easier to read because it becomes obvious if the used identifier is a field or local variable.
Further it prevents the introduction of bugs by adding a new local variable that hides a field.
internal sealed class Foo
{
private Int32 bar = 42;
private void Bar()
{
// Uncommenting the following line will change the
// semantics of the method and probably introduce
// a bug.
//var bar = 123;
Console.WriteLine(bar);
// This statement will not be affected.
Console.WriteLine(this.bar);
}
}
This can be avoided by using different naming conventions for fields and local variables but I really dislike underscore prefixed names. The first character of a word is very important for its readability and an underscore is one of the worst possible choices.

this is almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then use this. If you have a naming convention (such as naming all member fields something like _foo), then you really don't need to refer to them like this._foo.
It's a matter of personal taste (no performance penalty), but I find having the explicit this is harder to maintain and adds little value if you have a solid naming convention. Some people will only use this when calling a member method, e.g. this.Foo(_bar) instead of Foo(_bar), but again, I don't personally believe it adds much.
If you're working with existing code, follow the convention there, otherwise, pick whichever makes you the most productive and effective.

My rule of thumb: Never use 'this' when it is redundant. In this case, 'this' is redundant, so I would avoid it. A tool like ReSharper is very good at telling you when this is the case.

I always use this. to make it clear that I am referring to a class member, not a local variable.

I would try to be consistent, so that people don't get confused into thinking that the few you do the other way (apart from the way you normally pick) have some special significance.
If you don't use the _whatever naming convention for fields, then you should use this.whatever consistently because otherwise there will be problems when constructors take a whatever parameter and try to put in a whatever field.

It is fine. Especially since your class doesn't have a base class and the private fields are named appropriately. ReSharper considers this in your case to be redundant.

Should i use "this" with all occurrences of class variables within the class?
In your particular case, NO.
Consider however the following example:
class RssReader
{
private String url;
public bool FetchFeed (String url)
{
new XmlTextReader (url);
// vs.
new XmlTextReader (this.url);
return true;
}
}
Here you'll need to specify this to access the instance variable that has the same name as the method argument.

there is absolutely no reason not to use this. even redundancy is no reason not to use it, at all. You get the benefit of the intellisense box to safely complete your code and saves your time by selecting the right variable with the down-key and not to maul your keyboard all the time.

You may, but don't need to unless it's a method that takes arguments with the same names as your class vars (to distinguish them).

Well, as for me, 'this' looks really redundant when used with names starting with "_". This is absolutely legal in your example though.

Here is how I look at it. When you call a member (be it method, property or field) of a class as such like DoMyThing(); or return Property; within the instance scope, it's not necessary that you're calling an instance member. DoMyThing or Property can be static members too.
public class Abc
{
public static void Static()
{
}
public Xyz Instance;
public void Test() //instance scope
{
var xyz = Instance; //calls instance member
Static(); //calls static member
}
}
For both of them (static and instance) I've not prefixed anything. Actually my choices are:
do not prefix at all as above
public void Test()
{
var xyz = Instance;
Static();
}
prefix for instance members alone
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Static();
}
prefix for static members alone
public void Test()
{
var xyz = Instance;
Abc.Static(); //prefixes class
}
prefix in both cases
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Abc.Static(); //prefixes class
}
This answer is not to say one style is better than other. This is just personal preference. Each has its own claim for correctness and readability.
My take:
a. I for one do not like the inconsistent style of 2. and 3.
b. 1. has the advantage of being more readable for me. Prefixing makes it more about definition than intent.
c. 4. is all about correctness. It has the advantage of being extremely consistent, especially considering you would be forced to prefix for both instance and static members at some point anyway. This is even more important to consider when it comes to base keyword where if you dont prefix with base keyword for a base class member, then adding a member with the same name in current derived class will cause it to override the previous call, changing the whole dynamics.
Personally, I would go with 1. And use this or Abc sparingly when I'm forced to. It's more readable for me, a benefit for me that is good enough to compensate for the little inconsistency it might cause.

Whereas your code will work without ‘this’, it explicitly tells that you mean ‘this’ particular instance of the class. Some people find it easier to read, plus it can help avoid mistakes.
Imagine you made a mistake and wrote…
public string Name
{ get; private set; }
public Forest(string name)
{
name = Name; //these are written in the wrong order...
}
It’s an easy mistake to make given that it’s essentially the same word. Unfortunately the compiler will not catch it - it won’t throw an error. As a result your instance will be created but the property will not have its value assigned. On the other hand if you made the same mistake while using ‘this’…
public string Name
{ get; private set; }
public Forest(string name)
{
this.name = Name; //these are still written in the wrong order but with 'this' prefix...
}
the compiler will throw an error telling you that you are attempting to assign value to a non existent property.

Related

What does this code do in c# and what is it's purpose?

public class A {
public Par mParams;
public Par Parameters {
get { return mParams; }
set { mParams = value; }
}
}
I am new to c#
What is public Par Parameters? This seems neither a class or a function. Confused here.
Think of it like a public Par getParameters() and public void setX(Par p) method in Java. So, it is closest to a "function" but it is actually called Property. You can use it like this:
A myObject = new A();
a.Parameters = new Par(...);
This is a property which is backed by a public field, in this case, it is somewhat redundant, mParms should be declared as protected or private.
I recommend that you review this MSDN Programming Guide on Properties. It explains quite well, how they work and what they're used for.
The block of code from Public Par Parameters is a Property
I suspect the line public Par mParams; should actually be private. Its meant to be the underlying variable storing the value of the property.
Its worth pointing out that you do not explicitly need mParams any more in C#. You can define an automatic property, where the compiler creates its own underlying private variable using:
Public Par Parameters { get; set; }
public Par Parameters is a property, used to set or get the value of mParams.
Parameters is a Property of type Par. It has an access modifier (public), which means it is accessible from anywhere in your code.
Your example is a little redundant, because the mParams field is actually publicly accessible, and the property that exposes it doesn't do anything apart from returning and setting the field. However, you could potentially add extra code in each of the "accessors" (the get and set bits). For example to do validation, notify something that a property has been changed, etc.
You use properties in much the same way as fields:
A foo = new A();
// Calls the "get" accessor of the Parameters property
if (foo.Parameters == null)
{
// Calls the "set" accessor of the Parameters property
foo.Parameters = new Par();
}
It is considered a best practice to not allow direct access to member fields (variables) from outside a class. In a typical scenario, the field should therefore be private (or sometimes protected):
private Par mParams;
public Par Parameters
{
get { return mParams; }
set { mParams = value; }
}
There are a few slightly different syntaxes you will want to learn about as well. First, there is the auto-implemented property:
public Par Parameters
{
get;
set;
}
For auto-implemented properties, the C# compiler generates a backing field for you automatically. This saves you from writing some code if our property getter and setter don't need to contain any logic.
You can also use properties to restrict access in ways you cannot achieve with fields:
public Par Parameters
{
get;
private set;
}
Notice the set "accessor" has it's own access modifier. The result is a property that is publicly readable, but only the class itself is allowed to set it. This is similar to:
private Par mParams;
public Par Parameters
{
get { return mParams; }
}
Which does effectively the same thing, but without an auto-implemented property.
In languages that do not support properties, all this would be achieved by creating two methods: GetParameters and SetParameters. In fact, the C# compiler generates some very similarly named methods in the background.
It's shorthand for accessors and mutators. In another example:
private int i = 0;
public int myNumber {
get { return i; }
set { i = value; }
}
Allows you to change the variable i. Like so in code:
className.myNumber = 20;
// className.i is now 20
It's a property, which works very much like a pair of methods (functions) whose only purpose is to give you access to the mParams field. As a bit of syntactic sugar, C# gives you the ability to assign and read to it much as you would a variable. Think of it as two methods, getParameters and setParameters, which you can't call directly, but which are invoked when you access Parameters.
Parameters = new Par(); //Works as though you had run: setParameters(new Par());
Par x = Parameters; //Works as though you had run: Par x = getParameters();
This allows you to use the shorter, more convenient and expressive variable-like syntax, but what you're actually doing is running two "invisible" methods created by the compiler.

C# static class and data members question

I am not sure how to implement what I have in mind using C# .Net 3.5. I have a static class called Common which contains common methods. One of the method is PrepareReportParameters. This method accepts a string ReportParams and parse it to get the parameter values. I load this ReportParams string into a Dictionary . And then verify whether the required elements exist. I check that like:
if (ReportParamList.ContainsKey("PAccount"))
{
ReportParamList.TryGetValue("PAccount", out PrimaryAccount);
}
where PrimaryAccount is a static variable in my Common class. And I can access this elsewhere as Common.PrimaryAccount.
Though, this approcah of accessing the report parameters will work but I want PrimaryAccount to be accessed as Common.ReportParameters.PrimaryAccount.
Here is the problem, I don't know what type ReportParameters should be and how can I have all the report parameters added to this type? How should I define ReportParameters? Does it sound feasible or it doesn't make any sense. Please H E L P!
It sounds like you're basically used to using global variables to pass around state. That's generally a really bad idea.
Why doesn't your method just return the primary account value? That can then be passed to other things which need it.
If you find yourself with a lot of static members - and in particular if other classes are fetching mutable static variables - consider whether there's a more OO design you could apply. It'll be easier to understand, easier to test, and easier to maintain.
EDIT: Okay, so currently you have:
public static class Common
{
public static int PrimaryAccount;
// other static fields
public static void PrepareReportParameters(string reportParameters)
{
// Code to set the fields
}
}
Instead of that, use a normal class:
public class ReportParameters
{
public int PrimaryAccount { get; private set; }
// Other properties
private ReportParameters(int primaryAccount, ....)
{
this.PrimaryAccount = primaryAccount;
}
// Could use a constructor instead, but I prefer methods when they're going to
// do work
public static ReportParameters Parse(string report)
{
// Parse the parameter, save values into local variables, then
return new ReportParameters(primaryAccount, ...);
}
}
Then call this from the rest of your code, and pass the ReportParameters reference to anything that needs it.
You could create a class called ReportParameters with the relevant strongly-typed properties, and give Common a static instance of it?
I'm not sure this is the best design. Theres a certain amount of 'code smell' to having Common.PrimaryAccount only to be allowed to be accessed after PrepareReportParameters is called. Maybe you'd consider an instance class, passing in the parameters in the constructor?

Should a protected property in a C# child class hide access to a public property on the parent?

I have the following code:
public class Parent
{
public string MyField { get; set; }
}
public class Child : Parent
{
protected new int MyField { get; set; }
}
I try and access this with:
static void Main(string[] args)
{
Child child = new Child();
child.MyField = "something";
}
Visual studio 2008 compiles this without comment, but under Mono (2.4.2, Ubuntu) I get the error message
'HideTest.Child.MyField' is inaccessible due to its protection level (CS0122)
Is one implementation or the other more compliant with the standard here?
Edit: Thanks to all the people who have pointed out the bad design. Unfortunately it's a third-party library and changing it significantly isn't practical.
From ECMA-334 (the C# spec) §10.7.1.2 :
A declaration of a new member hides an inherited member only within the scope of the new member.
You can see this behavior by running this test on Microsoft's implementation.
using System;
using NUnit.Framework;
namespace ScratchPad
{
[TestFixture]
public class Class1
{
[Test]
public void InheritanceHiding()
{
var b = new Base();
var d = new Derived();
var baseSomeProperty = b.SomeProperty;
var derivedSomeProperty = d.SomeProperty;
b.GetSomeProperty();
d.GetSomeProperty();
}
}
public class Base
{
public string SomeProperty
{
get
{
Console.WriteLine("Getting Base.SomeProperty");
return "Base.SomeProperty";
}
}
public string GetSomeProperty()
{
return SomeProperty;
}
}
public class Derived : Base
{
protected new int SomeProperty
{
get
{
Console.WriteLine("Getting Derived.SomeProperty");
return 3; //Determined by random roll of the dice.
}
}
public new int GetSomeProperty()
{
return SomeProperty;
}
}
}
Which will output:
Getting Base.SomeProperty //(No Controversy)
Getting Base.SomeProperty //(Because you're calling from public scope and the new member is in protected scope, there is no hiding)
Getting Base.SomeProperty //(No Controversy)
Getting Derived.SomeProperty //(Now because you're calling from protected scope, you get the protected member).
So the property you're accessing from your Main() should be the base class property (as it is in MS.NET), not the derived property (as in Mono), because the new derived member only hides the 'old' base member in protected scope.
Mono is doing something wrong here according to the spec.
Jason's answer is correct but he asks for a justification of this behaviour. (Namely that a hiding method is only hiding within the scope of the hiding method.)
There are a number of possible justifications. One in particular is that this is yet another way in which the design of C# mitigates the Brittle Base Class problem.
FooCorp makes Foo.DLL:
public class Foo
{
public object Blah() { ... }
}
BarCorp makes Bar.DLL:
public class Bar : Foo
{
// stuff not having to do with Blah
}
ABCCorp makes ABC.EXE:
public class ABC
{
static void Main()
{
Console.WriteLine((new Bar()).Blah());
}
}
Now BarCorp says "You know, in our internal code we can guarantee that Blah only ever returns string thanks to our knowledge of our derived implementation. Let's take advantage of that fact in our internal code."
public class Bar : Foo
{
internal new string Blah()
{
object r = base.Blah();
Debug.Assert(r is string);
return (string)r;
}
}
ABCCorp picks up a new version of Bar.DLL which has a bunch of bug fixes that are blocking them. Should their build break because they have a call to Blah, an internal method on Bar? Of course not. That would be terrible. This change is a private implementation detail that should be invisible outside of Bar.DLL.
In general, the .NET implementation of C# should probably be considered "canon". From the documentation on the new Modifier:
A constant, field, property, or type introduced in a class or struct hides all base class members with the same name.
... it seems like the Mono implementation is more correct given this definition. It should be hiding the implementation of MyField in the Parent class, and therefore it should only be accessible with the int MyField signature from the Child class.
Prelude: This code is crazy. If you actually have code in your app like this, fix it now. Either make them both protected or both public!
Regarding the error: The CLR has a lot of really strange 'edge case' rules in it for dealing with things like this. The best place to look for this kind of stuff is usually Eric Lippert's blog.
In saying that though, it looks like mono is actually doing the more sensible thing here in my opinion.
On second look, the C# one makes more sense once you factor in the 'behind the scenes' stuff.
Properties are not "first class" in MSIL. A property in C# or VB is just compiled down to a get and set method (the compiler also sticks an attribute somewhere for bookkeeping).
int MyField { get; set; } will actually produce MSIL for two methods:
void set_MyField(int value);
int get_MyField();
Now, given that your new method has a different type, you'll end up with the following 2 setter methods.
void set_MyField(int value);
void set_MyField(string value);
When you call x.MyField = "string" you're just calling one of those methods. This then boils down to a normal method overloading scenario. It's perfectly valid to have two methods with the same name that take different parameters, so the compiler will just select the string one and carry on it's merry way.
So yeah. The C# one makes sense if you know how the internals work, the Mono one makes more sense if you don't.
Which one is "more correct"? Ask Eric Lippert :-)
Just adding my 2 cents) That's a Mono bug, here is the description.
IMHO the difference is that MS.NET recognize the type string for MyField and sets the value of Parent property and in Mono in just tries to access MyField in Child class.
You are making something that's available through the base class unavailable through the child. You can try that, but it won't actually do anything. People can always just do this:
Parent child = new Child();
and call the method. So if you want the field to be hidden, declare a new one and keep the inherited one public.

Is it bad practice to initialise fields outside of an explicit constructor [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Initialize class fields in constructor or at declaration?
We are arguing about coding practices. The examples here are a little too simple, but the real deal has several constructors. In order to initialise the simple values (eg dates to their min value) I have moved the code out of the constructors and into the field definitions.
public class ConstructorExample
{
string _string = "John";
}
public class ConstructorExample2
{
string _string;
public ConstructorExample2()
{
_string = "John";
}
}
How should it be done by the book? I tend to be very case by case and so am maybe a little lax about this kind of thing. However i feel that occams razor tells me to move the initialisation out of multiple constructors. Of course, I could always move this shared initialisation into a private method.
The question is essentially ... is initialising fields where they are defined as opposed to the constructor bad in any way?
The argument I am facing is one of error handling, but i do not feel it is relevant as there are no possible exceptions that won't be picked up at compile time.
Note that all such field declaration-level initialization will be performed once for each constructor-chain, even if the constructor by itself sets the field to something else.
If you chain constructors together, the fields will be initialized in the common, first, constructor that is called.
Look at this example:
using System;
namespace ClassLibrary3
{
public class Class1
{
private string _Name = "Lasse";
public Class1()
{
}
public Class1(int i)
: this()
{
}
public Class1(bool b)
{
_Name = "Test";
}
}
}
This code compiles as this:
using System;
namespace ClassLibrary3
{
public class Class1
{
private string _Name;
public Class1()
{
_Name = "Lasse"
}
public Class1(int i)
: this()
{
// not here, as this() takes care of it
}
public Class1(bool b)
{
_Name = "Lasse"
_Name = "Test";
}
}
}
It's not necessarily bad to initialize values outside of the constructor, and the problem you have here:
string _string;
public ConstructorExample2()
{
_string = "John";
}
Is that if you have multiple constructors you have to remember to either
1. Reinitialize _string in every constructor
2. Separate the logic out into a common method and call that method in every constructor
3. Call the constructor with the logic in it, from the other constructors. (Chain the constructors)
Now this isn't necessarily a problem, but you have to remember to do it. By initializing it outside of the constructor, it's done for you. It's one less thing you need to remember to do.
Microsoft FxCop by default recommends field initializers over using the constructor. This question is also a duplicate of this one and should provide some insight.
With static classes, you'll have to note some subtleties as addressed at this question.
In the above example the assignment of "John" to _string has no logical reliance on any variables and therefore it should be outside of the constructor in the field initializer.
So long as it is not possible to initialize the object in an non-usable state then it doesn't matter.
When the code is compiled both approaches will be the same anyway.
Not sure about C#, but in Java source code they seem to prefer the constructor, example:
public class String{
char[] value;
int offset;
...
public String(){
value = new char[0];
offset = 0;
...
}
}
I think for simple initializations like that it's fine to do it in the declaration. However, I don't understand the error handling argument. Even if there is an exception in the initialization, I think you will find that your normal error handling mechanism will work the same. It will still throw an exception when you call the constructor.
I tend to initialize things in the get accessor, where they are first used. If null then initialize and all that.
I prefer to initialize simple fields like that outside of the constructor.
It shouldn't cause any issues since compilation actually moves those initializations into the constructor at compile-time anyway.
If the initialization of the variable will be the same, no matter what arguments are passed to the constructor, then it doesn't make sense to clutter the constructor method with the unnecessary initialization code. In this case, I initialize in-place.
Inisialing the fields in the constructor is better. This way if/when a different constructor is added you know that all the fields are starting with null/default values and you can initialise them appropriately.

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}

Categories

Resources