C#: naming rules for protected members fields - c#

In our .NET software component we use the following naming convention. When a customer use our DLL from VB.NET, the compiler cannot distinguish distance member field from the Distance property. What workaround do you recommend?
Thanks.
public class Dimension : Text
{
private string _textPrefix;
protected double distance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance
{
get { return Math.Abs(distance); }
}
}

You should not use fields that are protected, for the reason that versioning and access cannot be guarded. See the Field Design guidelines. Change your field to a property, which will also force you to change to name (as you cannot have two properties with the same name). Or, if possible, make the protected field private.
To make setting your property accessible only to the inheriting classes, use a protected setter:
public class Dimension : Text
{
private string _textPrefix;
private double _absoluteDistance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance
{
get { return _absoluteDistance }
protected set { _absoluteDistance = Math.Abs(distance); }
}
}
Although that does cause divergence between get and set, as functionality is not the same. Perhaps a separate protected method would be better in this case:
public class Dimension : Text
{
private string _textPrefix;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance { get; private set; }
protected void SetAbsoluteDistance(double distance)
{
Distance = Math.Abs(distance);
}
}

Well, summarizing of what already being said you can do something like this :
public class Dimension : Text
{
private string _textPrefix;
private double _rawDistance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double AbsoluteDistance
{
get; private set;
}
/// <summary>
/// Gets the raw distance
/// </summary>
public double RawDistance
{
get { return _rawDistance; }
protected set { _rawDistance = value; AbsoluteDistance = Math.Abs(value); }
}
}
When RawDistance's value is set it also sets value for AbsoluteDistance and because of that there is no need to invoke Math.Abs() in getter of "AbsoluteDistance".

Related

Is there any reason to use very simple properties over fields?

I currently have this code written:
public class General
{
/// <summary>
/// Private variables.
/// </summary>
private const float fVersion = 1.3f;
private static bool bMonitoring = false;
/// <summary>
/// Retrieves the current version of the application.
/// </summary>
public static float Version
{
get
{
return fVersion;
}
}
/// <summary>
/// Are we monitoring performance?
/// </summary>
public static bool Monitoring
{
get
{
return bMonitoring;
}
set
{
bMonitoring = value;
}
}
}
In case I check for General.bMonitoring or General.Version often (maybe.. over 100 times a second!) and really care about performance: is it good practice to leave my class written like that, or should I simply delete these properties and make the fields public?
In this case if you aren't going to add some logic to the getter or setter then I would use static fields. Performance will be the same.
But if later you need extra logic when you set ot get values then it preffer to use properties because it allows for versioning and it gives you Encapsulation according to OOP principles. Don't care about performance
For Monitoring property you can use Auto-Implemented Property like
public static bool Monitoring { get; set; }
but in this case you need to implement a static constructor (thanks to #Mafii)
static General()
{
Monitoring = false;
}
or if you use C# 6.0 then just:
public static bool Monitoring { get; set; } = false;
Don't worry about performance. Property access is (and should be) very fast and compiler may inline them.
Property is preferred over field not because of performance, but because encapsulation and it will really helps when later you need for example checking or make property computed.
More by Jon Skeet http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

Static variable Behaviour in Asp.Net

I have a OperationHelper class which is as follows:
public class OperationHelper
{
/// <summary>
/// Gets or sets the Add Operation value
/// </summary>
public static bool AddOperation { get; set; }
/// <summary>
/// Gets or sets the Edit Operation value
/// </summary>
public static bool EditOperation { get; set; }
/// <summary>
/// Gets or sets the Delete Operation value
/// </summary>
public static bool DeleteOperation { get; set; }
/// <summary>
/// Gets or sets the Select Operation value
/// </summary>
public static bool SelectOperation { get; set; }
}
on each request this values are re-assigned. when i run this locally it works properly.
but when i published the code some values are not get assigned or not working as it should work.
So want to know the behavior of the static variable in Asp.Net with C#.
are static variable equal to global variable which is accessible to all user? If it is set by user A to true can user B get that value as True or it has different instance of the variable.
The behavior of static variables is that they are being created as soon as the code they belong to is reached. To solve your problem, consider a static constructor for your class to properly initialize all values to your desire
public class OperationHelper
{
/// <summary>
/// Gets or sets the Add Operation value
/// </summary>
public static bool AddOperation { get; set; }
/// <summary>
/// Gets or sets the Edit Operation value
/// </summary>
public static bool EditOperation { get; set; }
/// <summary>
/// Gets or sets the Delete Operation value
/// </summary>
public static bool DeleteOperation { get; set; }
/// <summary>
/// Gets or sets the Select Operation value
/// </summary>
public static bool SelectOperation { get; set; }
static OperationHelper() {
//initialize your static variables here
}
}
See here for a reference on static constructors.
So want to know the behavior of the static variable in Asp.Net with
C#.
are static variable equal to global variable which is accessible to
all user? If it is set by user A to true can user B get that value as
True or it has different instance of the variable.
The behavior is like that only if your run your site under one working process on your pool.
If your pool have more than one working process, then each process have their static values, and is unknown to you what process is given to each request, to each user. And process together they are not communicate.
So let say that you have a pool with 4 working process.
UserA ask for a page, Process 1 is replay and set a static value to A.
UserB ask for a page, Process 1 is replay and the static value is A.
UserA ask for a page, Process 2 is replay and the static value is not set.
and so on.
More on the subject:
Lifetime of ASP.NET Static Variable
Where are static variables stored in asp.net aspx page
Using static variables instead of Application state in ASP.NET
Static methods on ASP.NET web sites
Asp.net static object appears sometimes as non global
static variables are only created once. so userB will get same instance of the variable to answer your question.
More on this have been discussed here.
you need to consider session that will give you different value for each user accessing the site

How is the Memento Pattern implemented in C#4?

The Memento Pattern itself seems pretty straight forward. I'm considering implementing the same as the wikipedia example, but before I do are there any language features of C# that make it easier to implement or use?
One obvious feature would be generics, implementing an generic memento will allow you to use it for any object you want.
Many examples that you will see will use a string (including all those currently among the replies to this question) as state which is a problem since it's one of the few types in .NET which are immutable.
When dealing with mutable objects (like any reference type with a setter-property) you have to remember though that when you save the memento you need to create a deepcopy of the object. Otherwise whenever you change your original object you will change your memento.
You could do this by using a serializer like protobuf-net or json.net since they don't require you to mark your objects with serializable attribute like the normal .net serialization mechanism does.
Codeproject have few articles about generic memento implementations, but they tend to skip the deepcopy part:
Generic Memento Pattern for Undo-Redo in C#
Memento Design Pattern
I'm not aware of any already built-in way to support Memento pattern.
I see a couple of implementations by using .NET Mock frameworks, where in practise a clone of the object is created and can be field with a data, but I consider it kind of overhead.
The use Memento patter on Undo/Redo usually, probably you too. In this case, it's better to have as less data on Undo/Redo stack as possible, so the custom undoable object is something that I would go for.
Hope this helps.
There is one thing that will make this pattern marginally quicker to write in C# and that is that any state fields can be declared as public readonly so you don't need properties or 'get' methods to access them.
Here is a straight conversion with public readonly included.
class Originator
{
private string state;
// The class could also contain additional data that is not part of the
// state saved in the memento.
public void Set(string state)
{
Console.WriteLine("Originator: Setting state to " + state);
this.state = state;
}
public Memento SaveToMemento()
{
Console.WriteLine("Originator: Saving to Memento.");
return new Memento(state);
}
public void RestoreFromMemento(Memento memento)
{
state = memento.SavedState;
Console.WriteLine("Originator: State after restoring from Memento: " + state);
}
public class Memento
{
public readonly string SavedState;
public Memento(string stateToSave)
{
SavedState = stateToSave;
}
}
}
class Caretaker
{
static void Main(string[] args)
{
List<Originator.Memento> savedStates = new List<Originator.Memento>();
Originator originator = new Originator();
originator.Set("State1");
originator.Set("State2");
savedStates.Add(originator.SaveToMemento());
originator.Set("State3");
// We can request multiple mementos, and choose which one to roll back to.
savedStates.Add(originator.SaveToMemento());
originator.Set("State4");
originator.RestoreFromMemento(savedStates[1]);
}
}
I've found one using Generics here:
#region Originator
public class Originator<T>
{
#region Properties
public T State { get; set; }
#endregion
#region Methods
/// <summary>
/// Creates a new memento to hold the current
/// state
/// </summary>
/// <returns>The created memento</returns>
public Memento<T> SaveMemento()
{
return (new Memento<T>(State));
}
/// <summary>
/// Restores the state which is saved in the given memento
/// </summary>
/// <param name="memento">The given memento</param>
public void RestoreMemento(Memento<T> memento)
{
State = memento.State;
}
#endregion
}
#endregion
#region Memento
public class Memento<T>
{
#region Properties
public T State { get; private set; }
#endregion
#region Ctor
/// <summary>
/// Construct a new memento object with the
/// given state
/// </summary>
/// <param name="state">The given state</param>
public Memento(T state)
{
State = state;
}
#endregion
}
#endregion
#region Caretaker
public class Caretaker<T>
{
#region Properties
public Memento<T> Memento { get; set; }
#endregion
}
#endregion
#region Originator
public class Originator<T>
{
#region Properties
public T State { get; set; }
#endregion
#region Methods
/// <summary>
/// Creates a new memento to hold the current
/// state
/// </summary>
/// <returns>The created memento</returns>
public Memento<T> SaveMemento()
{
return (new Memento<T>(State));
}
/// <summary>
/// Restores the state which is saved in the given memento
/// </summary>
/// <param name="memento">The given memento</param>
public void RestoreMemento(Memento<T> memento)
{
State = memento.State;
}
#endregion
}
#endregion
#region Memento
public class Memento<T>
{
#region Properties
public T State { get; private set; }
#endregion
#region Ctor
/// <summary>
/// Construct a new memento object with the
/// given state
/// </summary>
/// <param name="state">The given state</param>
public Memento(T state)
{
State = state;
}
#endregion
}
#endregion
#region Caretaker
public class Caretaker<T>
{
#region Properties
public Memento<T> Memento { get; set; }
#endregion
}
#endregion
Used like this:
Originator<string> org = new Originator<string>();
org.State = "Old State";
// Store internal state in the caretaker object
Caretaker<string> caretaker = new Caretaker<string>();
caretaker.Memento = org.SaveMemento();
Console.WriteLine("This is the old state: {0}", org.State);
org.State = "New state";
Console.WriteLine("This is the new state: {0}", org.State);
// Restore saved state from the caretaker
org.RestoreMemento(caretaker.Memento);
Console.WriteLine("Old state was restored: {0}", org.State);
// Wait for user
Console.Read();
As #Simon Skov Boisen mentions this will only work for immutable data and requires a deep copy.

Class designs with collections within them, with collections within those

In a continuation of my previous thread, I have found that a lot of my classes contain collections. Eg:
Engine - contains collection of pistons - piston - contains collection of xyz parts
Thus there is a hierarchy, as every component contains a collection of parts, which goes on and on.
This is a coding scenario I have not come across before. Constantly writing code like so:
class Part (Replace Part with apt name)
{
List<APart> parts ...
}
And then the same for APart, as that contains a collection of inner parts, is very tedious and therefore making me question whether this is the right way to code.
Is there a better way to write this sort of code? Anything like AOP etc I am open to (Though AOP is for cross-cutting concerns).
One thought:
Your Engine class could contain a PistonsManager class, which manages the list of Pistons. The PistonsManager could contain all of the logic to modify the list and shield the Engine class from having to think about Pistons. By the same logic, your PistonsManager class could contain an XYZPartsManager. This way you aren't programming list logic/management into your Engine logic, but have classes to do that. It might make readability and make the logic flow nicely.
Sometimes coding is just tedious. However, there are often patterns that can be ferreted out of an implementation.
We have a situation similar to yours and discovered that there was an underlying recursive pattern. So we implemented a base class (call it Part) that itself can contain a List(Of Part). This can be as deep as needed.
The collection classes for specific class implementations are either generic collections of the specific type or implement an interface that allows us to get at specific data in the class (we had to implement the interface mechanism due to collection collisions in WCF).
The upshot is that you will probably have a lot of discrete Part inheritors, but your will will be a common way to instantiate, process, and traverse your elements with a common set of code.
Update
This is a severely contrived example, but one that should get you pointed in the right direction. In our application, we use a substantial amount of reflection and table-mapped class names in order to severely reduce the amount of repetitive code. This example reflects some of that behavior, but not all.
This example basically shows how you can have a generic part class which contains a recursive collection of parts which are indexed at the part type level. In other words, you will have Engine and Engine will have a collection of part collections indexed by part type. For example, Engine could have a collection of Pistons, a collection of hoses, etc. This design is obviously optional, but does make it somewhat easier to process.
Here are the main classes:
/// <summary>
/// The base part collection
/// </summary>
/// <remarks></remarks>
public class PartBase
{
/// <summary>
/// The key for the record, such as a recordid
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public virtual string CollectionKey {get; set;}
public PartBase() : base()
{
m_cParts = new PartBaseCollections();
}
public virtual void InitializeFromDataRow(DataRow oRow)
{
// ToDo: Either implement generic column/datarow mapping through reflection or have each class override this method
}
private PartBaseCollections m_cParts;
public PartBaseCollections Parts
{
get
{
return m_cParts;
}
}
public PartBaseCollection GetParts(string sTableName)
{
if (this.Parts.Contains(sTableName))
{
return this.Parts(sTableName);
}
else
{
PartBaseCollection cParts = new PartBaseCollection(sTableName);
this.Parts.Add(cParts);
return cParts;
}
}
public void AddParts(DataSet dsData)
{
foreach (DataTable oTable in dsData.Tables)
{
PartBaseCollection cParts = null;
cParts = GetParts(oTable.TableName);
cParts.AddRecordsFromTable(oTable);
}
}
}
/// <summary>
/// A collection of PartBases keyed by a value, such as a table name (for example, Pistons)
/// </summary>
/// <remarks></remarks>
public class PartBaseCollection : System.Collections.ObjectModel.KeyedCollection<string, PartBase>
{
public string CollectionKey {get; set;}
public Type RecordType {get; set;}
public PartBaseCollection(string TableName)
{
this.CollectionKey = TableName;
// Assume that the TableName is a class in the current namespace
RecordType = Type.GetType(this.GetType().Namespace + "." + TableName, false, true);
}
protected override string GetKeyForItem(PartBase item)
{
return item.CollectionKey;
}
public PartBase ManufactureRecord()
{
return Activator.CreateInstance(this.RecordType);
}
public void AddRecordsFromTable(DataTable oTable)
{
foreach (DataRow oRow in oTable.Rows)
{
PartBase oPart = null;
oPart = ManufactureRecord();
oPart.InitializeFromDataRow(oRow);
this.Add(oPart);
}
}
}
/// <summary>
/// All of the PartBaseCollection elements for a given PartBase
/// </summary>
/// <remarks></remarks>
public class PartBaseCollections : System.Collections.ObjectModel.KeyedCollection<string, PartBaseCollection>
{
protected override string GetKeyForItem(PartBaseCollection item)
{
return item.CollectionKey;
}
}
public class Engine : PartBase
{
}
public class Piston : PartBase
{
}
And here is an example of creating the engine:
public void CreateEngine()
{
DataSet dsData = new DataSet();
DataTable oTable = new DataTable("Piston");
dsData.Tables.Add(oTable);
Engine oEngine = new Engine();
oEngine.AddParts(dsData);
}
sounds like the composite design pattern - consider looking at the iterator design pattern and perhaps the visitor design pattern as these usually go together.

Fixing error: cannot reference a type through an expression

I'm developing a game. I want to have game entities each have their own Damage() function. When called, they will calculate how much damage they want to do:
public class CombatantGameModel : GameObjectModel
{
public int Health { get; set; }
/// <summary>
/// If the attack hits, how much damage does it do?
/// </summary>
/// <param name="randomSample">A random value from [0 .. 1]. Use to introduce randomness in the attack's damage.</param>
/// <returns>The amount of damage the attack does</returns>
public delegate int Damage(float randomSample);
public CombatantGameModel(GameObjectController controller) : base(controller) {}
}
public class CombatantGameObject : GameObjectController
{
private new readonly CombatantGameModel model;
public new virtual CombatantGameModel Model
{
get { return model; }
}
public CombatantGameObject()
{
model = new CombatantGameModel(this);
}
}
However, when I try to call that method, I get a compiler error:
/// <summary>
/// Calculates the results of an attack, and directly updates the GameObjects involved.
/// </summary>
/// <param name="attacker">The aggressor GameObject</param>
/// <param name="victim">The GameObject under assault</param>
public void ComputeAttackUpdate(CombatantGameObject attacker, CombatantGameObject victim)
{
if (worldQuery.IsColliding(attacker, victim, false))
{
victim.Model.Health -= attacker.Model.Damage((float) rand.NextDouble()); // error here
Debug.WriteLine(String.Format("{0} hits {1} for {2} damage", attacker, victim, attackTraits.Damage));
}
}
The error is:
'Damage': cannot reference a type
through an expression; try
'HWAlphaRelease.GameObject.CombatantGameModel.Damage'
instead
What am I doing wrong?
You need to associate a function with that delegate before you can invoke it.
You don't need a delegate here - with the code you have, you are better off having your Damage function as either an implementation of an interface, or have it declared as abstract (or virtual) in the base GameObjectModel class so that the derived classes can (or have to) override it.
You are actually declaring a nested delegate type named Damage, not an instance of that type. Think of it as the difference between a class an an instance of a class.
To actually use your delegate, you must declare a field, property or event to hold it.
For example:
// note that the delegate can be declared either in a class or outside of it.
public delegate int Damage(float randomSample);
public class CombatantGameModel /* ... */
{
/* ... */
public Damage DamageCalculator { get; set; }
}

Categories