|
It's a good idea to create a new List if you are going to return it to the outside world - remember that if you return a List, you actually return a reference to the list, so any changes made to it outside the class affect the version the class is using, but without you being notified. If you return a copy of a list then the outside world can do what it likes with the list without it affecting the one your class is using and potentially buggering up your data!
private List<string> _curveswithnodata = new List<string>();
public List<string> Curveswithnodata
{
get { return new List<string>(_curveswithnodata); }
set { _curveswithnodata = value; }
} The other solution is to return a read only version:
get { return _curveswithnodata.AsReadOnly());
But that returns a different type: ReadOnlyCollection<T> rather than List<T> which generally makes it harder to work with outside the class.
If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.
|
|
|
|
|
I am building a webservice (not WCF). I need to store two values (name,value pairs).
Instead of using List<string>, I used Dictionary<string,int>. But it give me error message saying "Can't serialize the dictionary object.
Which collections object I can use (to be able to serialize) to store name value pair in a webservice .
Thanks
|
|
|
|
|
Dictionaries are not serializable via SOAP or XML serializers - but they are via DataContractSerializer[^]
The only other option is to use a List<KeyValuePair<string, yourtype>> which (frankly) is a PITA!
But, a serializable PITA!
If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.
|
|
|
|
|
Griff,
Thanks. But you can't use this as a property of class. Can't have getters and setters.
nath
|
|
|
|
|
Maybe I just need sleep to recover from recent festivities - but I can't think of a way to fix this code to comply with the FX Cop warning.
The only thing that comes to mind is to create protected setters (or setter methods) in the base class and call those from the derived constructors...
public abstract class BaseClass
{
private int id;
protected BaseClass()
{
Initialize(out id);
}
public int Id { get { return id; } }
protected abstract void Initialize(out int id);
}
public class ConcreteA : BaseClass
{
public ConcreteA()
: base()
{ }
protected override void Initialize(out int id)
{
ConcreteAIntializationData data = NativeMethods.ConcreteAInitialize();
id = data.Id;
}
}
public class ConcreteB : BaseClass
{
private string name;
public ConcreteB()
: base()
{ }
protected override void Initialize(out int id)
{
ConcreteBIntializationData data = NativeMethods.ConcreteBInitialize();
id = data.Id;
name = data.name;
}
}
public static class NativeMethods
{
public static ConcreteAIntializationData ConcreteAInitialize()
{
return new ConcreteAIntializationData();
}
public static ConcreteBIntializationData ConcreteBInitialize()
{
return new ConcreteBIntializationData();
}
}
public class ConcreteAIntializationData
{
private int id;
public ConcreteAIntializationData()
{
id = 1;
}
public int Id
{
get { return id; }
}
}
public class ConcreteBIntializationData
{
private int id;
public string name;
public ConcreteBIntializationData()
{
id = 2;
name = "Name";
}
public int Id
{
get { return id; }
}
public string Name
{
get { return name; }
}
}
|
|
|
|
|
Simple, don't use FX Cop.
I didn't read that too closely, but shouldn't the (derived) constructor pass whatever to the base constructor?
I'm not a fan of the Initialize pattern either.
Sooo... I guess just ignore me.
|
|
|
|
|
This is one of those 'well it depends' rules. Think about the order in which chained constructors are called. The first thing derived class B's constructor does is call base class A's constructor.
If A's constructor now calls a virtual instance method defined in class B, it is accessing a partially initialised class. Remember that B's constructor has not run yet and all of B's instance data will be in an unknown state but it will be perfectly safe to call the instance method as long as it does not rely on instance data.
Examples of situations where this technique is used can be seen in the System.Windows.Forms class. Here you will find the protected bool ShowWithoutActivation property which is called internally and in the base class returns the constant value false. Overriding to return constant true changes the behaviour of a derived class. Similarly the property CreateParams can also be overridden to supply non default parameters to the base class.
So my feeling is it's OK to ignore CA2214 as long as you treat the overridden method or property as if it were static and don't do anything naughty.
Alan.
|
|
|
|
|
Cheers Alan!
Alan N wrote: don't do anything naughty
The overridden method is purely setting instance fields unique to that class to their initial values (these are not changed anywhere after instanciation - that part of the derived classes is immutable) and returning initialization values that are common to all derived classes to the base's constructor.
It seems like I should be OK to suppress the warning in this scenario.
|
|
|
|
|
The way I tend to code this type of code is to have an instance method call the override versions, like this:
public abstract class MyBase
{
public MyBase()
{
Initialize();
}
private void Initialize()
{
OnInitialize();
}
protected virtual void OnInitialize()
{
}
} Why do I do this you may ask? Well, I tend to have a separation of design time code, and runtime code, and this allows me to easily separate things out.
|
|
|
|
|
Does that dodge the warning? If so, that's pretty rubbish on FXCop's part since that's 'bad' for exactly the same reason.
|
|
|
|
|
Yes it does, and there's nothing wrong with doing this. The problem with FxCop is that it's very arbitrary with its rules, many of which are excessively anal.
|
|
|
|
|
I'll check this later - I'm pretty sure on VS2012 when I tried this yesterday before posting it just added something into the warning about a call chain or similar but still CA2214
|
|
|
|
|
In VS2012 you still get the warning
contains a call chain that results in a call to a virtual method defined by the class
|
|
|
|
|
DaveyM69 wrote: The overridden method is purely setting instance fields unique to that class to
their initial values (these are not changed anywhere after instanciation - that
part of the derived classes is immutable) and returning initialization values
that are common to all derived classes to the base's constructor.
As I read that...
Yes that can lead to problems.
And that is what the constructor is supposed to do - iniatialize the class variables.
Also why would the base ctor care about child initialization values when all the base ctor should be doing is initializing the base ctor?
|
|
|
|
|
jschell wrote: why would the base ctor care about child initialization values when all the base
ctor should be doing is initializing the base ctor
The child needs to self initialize with values retrieved from an unmanaged function call (the function is different for each child type) - then pass the common values to the base so it can initialize itself.
What I was trying to do was force a method to be called when the base constructor runs that
1. calls the unmanaged function (hence it needing to be in called from the child as only the child should know what unmanaged function to call, and therefore needs to be an abstract method)
2. the child initializes it's unique fields
3. passes the common values back into the base constructor (hence the out parameters)
Perhaps this code will make it clearer...
public abstract class Base
{
private int commonValue1;
private int commonValue2;
private int id;
protected Base(int id)
{
this.id = id;
Initialize(out commonValue1, out commonValue2);
}
public int CommonValue1
{
get { return commonValue1; }
}
public int CommonValue2
{
get { return commonValue2; }
}
public int Id
{
get { return id; }
}
protected abstract void Initialize(out int commonValue1, out int commonValue2);
}
public class ChildA : Base
{
public ChildA(int id)
: base(id)
{ }
protected override void Initialize(out int commonValue1, out int commonValue2)
{
DataA data;
NativeMethods.UnmanagedFunctionGetChildAData(Id, out data);
commonValue1 = data.Value1;
commonValue2 = data.Value2;
}
}
public class ChildB : Base
{
private int childBValue;
public ChildB(int id)
: base(id)
{ }
public int ChildBValue { get { return childBValue; } }
protected override void Initialize(out int commonValue1, out int commonValue2)
{
DataB data;
NativeMethods.UnmanagedFunctionGetChildBData(Id, out data);
commonValue1 = data.Value1;
commonValue2 = data.Value2;
childBValue = data.Value3;
}
}
public class ChildC : Base
{
private int childCValue1;
private int childCValue2;
public ChildC(int id)
: base(id)
{ }
public int ChildCValue1 { get { return childCValue1; } }
public int ChildCValue2 { get { return childCValue2; } }
protected override void Initialize(out int commonValue1, out int commonValue2)
{
DataC data;
NativeMethods.UnmanagedFunctionGetChildCData(Id, out data);
commonValue1 = data.Value1;
commonValue2 = data.Value2;
childCValue1 = data.Value3;
childCValue2 = data.Value4;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct DataA
{
private int value1;
private int value2;
public int Value1 { get { return value1; } }
public int Value2 { get { return value2; } }
}
[StructLayout(LayoutKind.Sequential)]
internal struct DataB
{
private int value1;
private int value2;
private int value3;
public int Value1 { get { return value1; } }
public int Value2 { get { return value2; } }
public int Value3 { get { return value3; } }
}
[StructLayout(LayoutKind.Sequential)]
internal struct DataC
{
private int value1;
private int value2;
private int value3;
private int value4;
public int Value1 { get { return value1; } }
public int Value2 { get { return value2; } }
public int Value3 { get { return value3; } }
public int Value4 { get { return value4; } }
}
internal static class NativeMethods
{
public static void UnmanagedFunctionGetChildAData(int id, out DataA data)
{
data = new DataA();
}
public static void UnmanagedFunctionGetChildBData(int id, out DataB data)
{
data = new DataB();
}
public static void UnmanagedFunctionGetChildCData(int id, out DataC data)
{
data = new DataC();
}
}
modified 3-Jan-13 18:03pm.
|
|
|
|
|
I use a similar pattern, but instead of private member variables in the abstract base class and passing them as out parameters, I use protected member variables and call a parameterless function (the derived class may access them in other overridable functions). Visual Studio 2010 gives that CA2214 warning, too.
I feel comfortable with this pattern, and ignore the warning.
|
|
|
|
|
DaveyM69 wrote: Perhaps this code will make it clearer...
And what do you think is the problem with making the based members protected?
Or providing a protected setter for those members?
|
|
|
|
|
jschell wrote: based members protected
Non private fields are generally not considered a great idea.
jschell wrote: protected setter for those members
No problem with that, but it implies to inheriting classes that the fields that are protected by the property can be changed after initialization which is not the case - easy to protect against in code and so long as I document this well then that's OK.
|
|
|
|
|
DaveyM69 wrote: Non private fields are generally not considered a great idea.
But calling child methods in a ctor is?
DaveyM69 wrote: it implies to inheriting classes that the fields that are protected by the property can be changed after initialization
A child can misuse the contract with a parent in any number of ways. There is no way to prevent that.
|
|
|
|
|
The reason this is a warning is because you can get yourself into some really nasty messes by doing this, if you don't understand it. The virtual method that you override in the subclasses is run with an incompletely initialised object – in particular its own constructor has not yet run so you don't have access to any instance variables, even those set in a constructor or in field initialisers (as they're compiled into the constructor too).
You've obviously simplified your example a lot and in this case you can provide a protected setter for Id and create the specific data objects in the subclass constructors. I'd say that's a better approach if it's possible.
|
|
|
|
|
Yeah, that's quite possible and may be what I end up doing.
I'd like to mark the relevant fields (at least in the base) read only ideally which is primarily why I'm trying to manipulate from the constructor, along with the fact that this is all to do with construction of the objects so it is the logical place!
|
|
|
|
|
I'm making a music player in C# wpf. I have a listview which itemssource is an observable collection. The song which is currently playing is the song at the current ActiveIndex,
public int ActiveIndex { get; set; }
Not the song at the listview selected index. ActiveIndex changes only when a user double clicks a song in the listview or when he presses the next/previous buttons.
I have a style for a listview row when listview selected index changes, now I want to color the background of a row when the active index changes. I'm thinking this could somehow be done with datatriggers but I have no idea how to do it.
|
|
|
|
|
Hi. I'm probably making some subtle (or more likely not so subtle) error. I'm trying to drive MMC via a C# program. I can, as a trial, get to the menus of Calc.exe via this code:
Process calcProcess=Process.Start("c:\\windows\\system32\\calc.exe");
Thread.Sleep(2000);
AutomationElement aeDesktop = AutomationElement.RootElement;
AutomationElement aeCalc = null;
int numWaits = 0;
do
{
aeCalc = aeDesktop.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "Calculator"));
Console.WriteLine("Looking for calculator . . . ");
++numWaits;
Thread.Sleep(100);
} while (aeCalc == null && numWaits < 10);
if (aeCalc == null)
throw new Exception("Failed to find calc.EXE");
else
Console.WriteLine("Found it!");
AutomationElementCollection menuCalcBars = aeCalc.FindAll(TreeScope.Children, new PropertyCondition(
AutomationElement.ControlTypeProperty, ControlType.MenuBar));
And I get a Count of 1 (for the one menu). BUT when I do this with MMC, I get a count of 0, no menu. In UISpy I can see the Calc menu but I can't see the MMC menu. Any help is GREATLY appreciated.
Ron
|
|
|
|
|
hi
I want the program to c# a folder on my system Transfer to another system in the network
|
|
|
|
|
we dont provide any programs here we provide solutions to the problems for ppl like you. None is going to write a program for you here but ready to help you when you are stuck with your programs.
you can use FileCopy[^] method to copy/move your files?
Jibesh V P
|
|
|
|